Part Number Hot Search : 
75010 V400CBTC 53290 HEF4027 APT15 24LC0 LD6805 UPD16875
Product Description
Full Text Search
 

To Download ATXMEGA128A1-CUR Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  features ? high performance, low power avr ? 8-bit microcontroller ? advanced risc architecture ? 135 powerful instructions ? most single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? up to 16 mips throughput at 16 mhz ? on-chip 2-cycle multiplier ? non-volatile program and data memories ? 16/32k bytes of in-system self-programmable flash (atmega16u4/atmega32u4) ? 1.25/2.5k bytes internal sram (atmega16u4/atmega32u4) ? 512bytes/1k bytes internal eeprom (atmega16u4/atmega32u4) ? write/erase cycles: 10,000 flash/100,000 eeprom ? data retention: 20 years at 85 c/ 100 years at 25 c (1) ? optional boot code section with independent lock bits in-system programming by on-chip boot program true read-while-w rite operation all supplied parts are preprogramed with a default usb bootloader ? programming lock for software security ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities a ccording to the jtag standard ? extensive on-chip debug support ? programming of flas h, eeprom, fuses, and lock bits through the jtag interface ? usb 2.0 full-speed /low speed device module with in terrupt on tran sfer completion ? complies fully with universal serial bus specification rev 2.0 ? supports data transfer rates up to 12 mbit/s and 1.5 mbit/s ? endpoint 0 for control transfers: up to 64-bytes ? 6 programmable endpoints with in or out directions and with bulk, interrupt or isochronous transfers ? configurable endpoints size up to 256 bytes in double bank mode ? fully independent 832 bytes usb dp ram for endpoint memory allocation ? suspend/resume interrupts ? cpu reset possible on usb bus reset detection ? 48 mhz from pll for full-speed bus operation ? usb bus connection /disconnection on microcontroller request ? crystal-less operation for low speed mode ? peripheral features ? on-chip pll for usb and high speed timer: 32 up to 96 mhz operation ? one 8-bit timer/counter with se parate prescaler and compare mode ? two 16-bit timer/counter with separate prescaler, compare- and capture mode ? one 10-bit high-speed timer/counter with pll (64 mhz) and compare mode ? four 8-bit pwm channels ? four pwm channels with programmabl e resolution from 2 to 16 bits ? six pwm channels for high speed operation, with programmable resolution from 2 to 11 bits ? output compare modulator ? 12-channels, 10-bit adc (features differen tial channels with programmable gain) ? programmable serial usart with hardware flow control ? master/slave spi serial interface 8-bit microcontroller with 16/32k bytes of isp flash and usb controller atmega16u4 atmega32u4 preliminary 7766f?avr?11/10
2 7766f?avr?11/10 atmega16/32u4 ? byte oriented 2-wire serial interface ? programmable watchdog timer with separate on-chip oscillator ? on-chip analog comparator ? interrupt and wake-up on pin change ? on-chip temperature sensor ? special microcontroller features ? power-on reset and programmable brown-out detection ? internal 8 mhz calibrated oscillator ? internal clock prescaler & on-the-fly clock switching (int rc / ext osc) ? external and internal interrupt sources ? six sleep modes: idle, adc noise reduction, power- save, power-down, standby, and extended standby ? i/o and packages ? all i/o combine cmos outputs and lvttl inputs ? 26 programmable i/o lines ? 44-lead tqfp package, 10x10mm ? 44-lead qfn package, 7x7mm ? operating voltages ? 2.7 - 5.5v ? operating temperature ? industrial (- 40c to +85c) ? maximum frequency ? 8 mhz at 2.7v - industrial range ? 16 mhz at 4.5v - industrial range note: 1. see ?data retention? on page 8 for details.
3 7766f?avr?11/10 atmega16/32u4 1. pin configurations figure 1-1. pinout atmega16u4/atmega32u4 2. overview the atmega16u4/atmega32u4 is a low-power cmos 8-bit microcontroller based on the avr enhanced risc architecture. by executing powerful instructions in a single clock cycle, the atmega16u4/atmega32u4 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consumption versus processing speed. atmega32u4 atmega16u4 44-pin qfn/tqfp uvcc d- d+ ugnd ucap vbus (ss/pcint0) pb0 (int.6/ain0) pe6 (pcint1/sclk) pb1 (pdi/pcint2/mosi) pb2 (pdo/pcint3/miso) pb3 (pcint7/oc0a/oc1c/rts) pb7 reset vcc gnd xtal2 xtal1 (oc0b/scl/int0) pd0 (sda/int1) pd1 (rxd1/int2) pd2 (txd1/int3) pd3 (xck1/cts) pd5 pe2 (hwb) pc7 (icp3/clk0/oc4a) pc6 (oc3a/oc4a) pb6 (pcint6/oc1b/oc4b/adc13) pb4 (pcint4/adc11) pd7 (t0/oc4d/adc10) pd6 (t1/oc4d/adc9) pd4 (icp1/adc8) avcc gnd aref pf0 (adc0) pf1 (adc1) pf4 (adc4/tck) pf5 (adc5/tms) pf6 (adc6/tdo) pf7 (adc7/tdi) gnd vcc index corner 1 2 3 4 5 6 7 8 9 10 11 33 32 31 30 29 28 27 26 25 24 23 12 13 14 15 16 17 18 19 20 21 22 44 43 42 41 40 39 38 37 36 35 34 pb5 (pcint5/oc1a/oc4b/adc12) avcc gnd
4 7766f?avr?11/10 atmega16/32u4 2.1 block diagram figure 2-1. block diagram the avr core combines a rich instruction set with 32 general purpose working registers. all the 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulting architecture is more code efficient while achiev ing throughputs up to ten times faster than con- ventional cisc microcontrollers. the atmega16u4/atmega32u4 provides the following features: 16/32k bytes of in-system programmable flash with read-while-writ e capabilities, 512bytes/1k bytes eeprom, 1.25/2.5k bytes sram, 26 general purpose i/o lines (cmos outputs and lvttl inputs), 32 general purpose working registers, four flexible timer/counters with compare modes and pwm, one more high-speed timer/counter with comp are modes and pll adjustable source, one usart (including cts/rts flow control signals), a byte oriented 2-wire serial interface, a 12- program counter stack pointer program flash mcu control register general purpose registers instruction register timers/ counters instruction decoder data dir. reg. port b data dir. reg. port e data dir. reg. port d data register port b data register port e data register port d interrupt unit eeprom spi status register sram usart1 z y x alu port b drivers port e drivers port f drivers port d drivers port c drivers pb7 - pb0 pe6 pf7 - pf4 reset vcc gnd xtal1 xtal2 control lines pc7 internal oscillator watchdog timer 8-bit da ta bus usb 2.0 timing and control oscillator calib. osc data dir. reg. port c data register port c on-chip debug jtag tap programming logic boundary- scan data dir. reg. port f data register port f por - bod reset pd7 - pd0 two-wire serial interface pll high speed timer/pwm pe2 pc6 pf1 pf0 on-chip usb pad 3v regulator uvcc ucap 1uf analog comparator vbus dp dm adc agnd aref avcc temperature sensor
5 7766f?avr?11/10 atmega16/32u4 channels 10-bit adc with optional differential input stage with programmable gain, an on-chip calibrated temperature sensor, a programmable watch dog timer with internal oscillator, an spi serial port, ieee std. 1149.1 comp liant jtag test interface, also used for access ing the on-chip debug system and programming and six software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, spi port, and interrupt system to continue functioning. the power-down mode saves the register contents but freezes the oscillator, disabling all other ch ip functions until the next interr upt or hardware reset. the adc noise reduction mode stops the cpu and all i/o modules except adc, to minimize switching noise during adc conver sions. in standby mode, the crysta l/resonator oscillator is running while the rest of the device is sleeping. this allows very fast start-up combined with low power consumption. the device is manufactured using atmel?s hi gh-density nonvolatile memory technology. the on-chip isp flash allows the program memory to be reprogrammed in -system through an spi serial interface, by a conventi onal nonvolatile memory programmer, or by an on-chip boot pro- gram running on the avr core. the boot program can use any interface to download the application program in the application flash memo ry. software in the boot flash section will continue to run while the application flash se ction is updated, providing true read-while-write operation. by combining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel atmega16u4/atmega32u4 is a powerful microcontroller that pro- vides a highly flexible and cost effective solution to many embedded control applications. the atmega16u4/atmega32u4 avr is supported with a full suite of program and system development tools including: c compilers, macro assemblers, program debugger/simulators, in- circuit emulators, and evaluation kits. 2.2 pin descriptions 2.2.1 vcc digital supply voltage. 2.2.2 gnd ground. 2.2.3 port b (pb7..pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b has better driving capabilities than the other ports. port b also serves the functions of various special features of the atmega16u4/atmega32u4 as listed on page 72 . 2.2.4 port c (pc7,pc6) port c is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port c output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port c pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. the port c pins are tri-stated when a reset condition becomes active, even if the clock is not running.
6 7766f?avr?11/10 atmega16/32u4 only bits 6 and 7 are present on the product pinout. port c also serves the functions of special features of the atmega16u4/atmega32u4 as listed on page 75 . 2.2.5 port d (pd7..pd0) port d is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port d pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of various special features of the atmega16u4/atmega32u4 as listed on page 77 . 2.2.6 port e (pe6,pe2) port e is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port e output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port e pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port e pins are tri-stated when a reset condition becomes active, even if the clock is not running. only bits 2 and 6 are present on the product pinout. port e also serves the functions of various special features of the atmega16u4/atmega32u4 as listed on page 80 . 2.2.7 port f (pf7..pf4, pf1,pf0) port f serves as analog inputs to the a/d converter. port f also serves as an 8-bit bi-directional i/ o port, if the a/d converter channels are not used. port pins can provide internal pull-up resistors (selected for each bit). the port f output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port f pins that are externa lly pulled low will source cu rrent if the pull- up resistors are activated. the port f pins are tri-stated when a reset condition becomes active, even if the clock is not running. bits 2 and 3 are not present on the product pinout. port f also serves the functions of the jtag interface. if the jtag interface is enabled, the pull- up resistors on pins pf7(tdi), pf5(tms), and pf 4(tck) will be activated even if a reset occurs. 2.2.8 d- usb full speed / low speed negative data upstream port. should be connected to the usb d- connector pin with a serial 22 ohms resistor. 2.2.9 d+ usb full speed / low speed positive data upstream port. should be connected to the usb d+ connector pin with a serial 22 ohms resistor. 2.2.10 ugnd usb pads ground.
7 7766f?avr?11/10 atmega16/32u4 2.2.11 uvcc usb pads internal regulator input supply voltage. 2.2.12 ucap usb pads internal regulator output supply voltage. should be connected to an external capac- itor (1f). 2.2.13 vbus usb vbus monitor input. 2.2.14 reset reset input. a low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. the minimum pulse length is given in table 8-1 on page 50 . shorter pulses are not guaranteed to generate a reset. 2.2.15 xtal1 input to the inverting oscillato r amplifier and input to the in ternal clock operating circuit. 2.2.16 xtal2 output from the invert ing oscillator amplifier. 2.2.17 avcc avcc is the supply voltage pin (input) for all the a/d converter channels. if the adc is not used, it should be externally connected to v cc . if the adc is used, it should be connected to v cc through a low-pass filter. 2.2.18 aref this is the analog reference pin (input) for the a/d converter.
8 7766f?avr?11/10 atmega16/32u4 3. about 3.1 disclaimer typical values contained in this datasheet ar e based on simulations and characterization of other avr microcontrollers manufactured on the same process technology. min and max values will be available after the device is characterized. 3.2 resources a comprehensive set of development tools, app lication notes and datasheets are available for download on http:// www.atmel.com/avr. 3.3 code examples this documentation contains simple code examples that briefly show how to use various parts of the device. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documen- tation for more details. these code examples assume that the part specific header file is included before compilation. for i/o registers located in extended i/o map, "i n", "out", "sbis", "sbic", "cbi", and "sbi" instructions must be replaced with instructio ns that allow access to extended i/o. typically "lds" and "sts" combined with "sbrs", "sbrc", "sbr", and "cbr". 3.4 data retention reliability qualification results show that the pr ojected data retention failure rate is much less than 1 ppm over 20 years at 85c or 100 years at 25c.
9 7766f?avr?11/10 atmega16/32u4 4. avr cpu core 4.1 introduction this section discusses the avr core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. 4.2 architectural overview figure 4-1. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipelining. while one instruction is being executed, the next instruc- tion is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom data bus 8-bit data sram direct addressing indirect addressing interrupt unit spi unit watchdog timer analog comparator i/o module 2 i/o module1 i/o module n
10 7766f?avr?11/10 atmega16/32u4 the fast-access register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle ar ithmetic logic unit (alu ) operation. in a typ- ical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16-b it indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic opera- tion, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and uncon ditional jump and call instructions, able to directly address the whole address space. most avr instructions have a single 16-bit word for- mat. every program memory address contains a 16- or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the application program section. both sections have dedicated lock bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the to tal sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control r egisters in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector posi- tion. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functi ons as control regis- ters, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. in addition, the atmega16u4/atmega32u4 has extended i/o space from 0x60 - 0x0ff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 4.3 alu ? arithm etic logic unit the high-performance avr alu operates in dire ct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set? section for a detailed description.
11 7766f?avr?11/10 atmega16/32u4 4.4 status register the status register contains information about the result of the most recently executed arithme- tic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status register is updated after all alu operations, as specified in the instruction set reference. this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for th e interrupts to be enabled. the individual inter- rupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i-bit can also be set and cleared by the application with the sei and cli instructions, as described in the instruction set reference. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (b it store) use the t-bit as source or desti- nation for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in so me arithmetic operations. half carry is useful in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the negative flag n and the two?s complement overflow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v suppor ts two?s arithmetic complements. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. bit 76543210 i thsvnzcsreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
12 7766f?avr?11/10 atmega16/32u4 ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logic operation. see the ?instruction set description? for de tailed information. 4.5 general purpose register file the register file is optimized for the avr enhanc ed risc instruction set. in order to achieve the required performance and flex ibility, the following in put/output schemes ar e supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 4-2 shows the structure of the 32 general purpose working registers in the cpu. figure 4-2. avr cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 4-2 , each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being physically imple- mented as sram locations, this memory organization provides great flexibility in access of the registers, as the x-, y- and z-pointer registers can be set to index any register in the file. 4.5.1 the x-register, y-register, and z-register the registers r26..r31 have some added functions to their general purpose usage. these reg- isters are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 4-3 . 70addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
13 7766f?avr?11/10 atmega16/32u4 figure 4-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the instruction set reference for details). 4.6 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer register always points to the top of the stack. note that the stack is implemented as growing from higher memory loca- tions to lower memory locations. this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are located. this stack space in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. the stack pointer must be set to point above 0x0100. the initial value of the stack pointer is the last address of the internal sram. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by three when the return address is pushed onto the stack with subroutine call or interrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by three when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8- bit registers in the i/o space. the number of bits actually used is implementation dependent. note that the data space in some implementa- tions of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x-register 707 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 707 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7070 r31 (0x1f) r30 (0x1e) bit 1514131211109 8 sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 1 0 0 0 0 0 11111111
14 7766f?avr?11/10 atmega16/32u4 4.6.1 extended z-pointer register for elpm/spm - rampz for elpm/spm instructions, the z-pointer is a concatenation of rampz, zh, and zl, as shown in figure 4-4. note that lpm is not affected by the rampz setting. figure 4-4. the z-pointer used by elpm and spm the actual number of bits is implementation depen dent. unused bits in an implementation will always read as zero. for compatibility with future devices, be su re to write these bits to zero. 4.7 instruction execution timing this section describes the general access timi ng concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no internal clo ck division is used. figure 4-5 shows the parallel instruction fetches and instruction executions enabled by the har- vard architecture and the fast-access register file concept. this is the basic pipelining concept to obtain up to 1 mips per mhz with the corr esponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 4-5. the parallel instruction fetches and instruction executions figure 4-6 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destina- tion register. bit 7654321 0 rampz7 rampz6 rampz5 rampz4 rampz3 rampz2 rampz1 rampz0 rampz read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit (individually) 7 0 7 0 7 0 rampz zh zl bit (z-pointer) 23 16 15 8 7 0 clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu
15 7766f?avr?11/10 atmega16/32u4 figure 4-6. single cycle alu operation 4.8 reset and inte rrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in orde r to enable the interrupt. depending on the program counter value, interrupts may be automatically disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see the section ?memory program- ming? on page 346 for details. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 61 . the list also determines the priority levels of the different interrupts. the lower the address the higher is the priority level. reset has the highest priority, and next is int0 ? the external interrupt request 0. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the mcu control r egister (mcucr). refer to ?interrupts? on page 61 for more information. the reset vector can also be moved to the start of the boot flash section by programming the bootrst fuse, see ?memory programming? on page 346 . when an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are dis- abled. the user software can write logic one to the i-bit to enable nested interrupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the fi rst type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vec- tor in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt fl ag will be set and remember ed until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is clea red, the corres ponding interrupt fl ag(s) will be set and remembered until the global interrupt enable bit is set, and will then be exec uted by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the in terrupt will not be triggered. when the avr exits from an inte rrupt, it will always retu rn to the main pr ogram and execute one more instruction before any pending interrupt is served. total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
16 7766f?avr?11/10 atmega16/32u4 note that the status register is not automatica lly stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the interrup ts will be immediately disabled. no interrupt will be executed af ter the cli instruction, even if it occurs simultaneously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. when using the sei instruction to enable interr upts, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ __disable_interrupt(); eecr |= (1< 17 7766f?avr?11/10 atmega16/32u4 4.8.1 interrupt response time the interrupt execution response for all the enab led avr interrupts is five clock cycles minimum. after five clock cycles the program vector address for the actual interrupt handling routine is exe- cuted. during these five clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. if an interrupt occurs w hen the mcu is in sleep mode, the interrupt exe- cution response time is increased by five cloc k cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine takes fi ve clock cycles. during these five clock cycles, the program counter (three bytes) is popped back from the stack, the stack pointer is incre- mented by three, and the i-bit in sreg is set. assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) c code example __enable_interrupt(); /* set global interrupt enable */ __sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
18 7766f?avr?11/10 atmega16/32u4 5. avr atmega16u4/atmega32u4 memories this section describes the different memo ries in the atmega16u4/atmega32u4. the avr architecture has two main memory spaces, the data memory and the program memory space. in addition, the atmega16u4/atmega32u4 features an eeprom memory for data storage. all three memory spaces are linear and regular. notes: 1. byte address. 2. word (16-bit) address. 5.1 in-system reprogrammable flash program memory the atmega16u4/atmega32u4 contains 16/32k bytes on-chip in-system reprogrammable flash memory for program storage. since all avr instructions are 16 or 32 bits wide, the flash is organized as 16k x 16. for software security, the flash program memory space is divided into two sections, boot program section and application program section. the flash memory has an en durance of at le ast 100,000 write/erase cycles. the atmega16u4/atmega32u4 program counter (pc) is 16 bits wide, thus addressing the 32k program memory locations. the operation of boot program section and associated boot lock bits for software protection are described in detail in ?memory programming? on page 346 . table 5-1. memory mapping. memory mnemonic atmega32u4 atmega16u4 flash size flash size 32k bytes 16k bytes start address - 0x0000 end address flash end 0x7fff (1) 0x3fff (2) 0x3fff (1) 0x1fff (2) 32 registers size - 32 bytes 32 bytes start address - 0x0000 0x0000 end address - 0x001f 0x001f i/o registers size - 64 bytes 64 bytes start address - 0x0020 0x0020 end address - 0x005f 0x005f ext i/o registers size - 160 bytes 160 bytes start address - 0x0060 0x0060 end address - 0x00ff 0x00ff internal sram size isram size 2,5k bytes 1.25k bytes start address isram start 0x100 0x100 end address isram end 0x0aff 0x05ff external memory not present. eeprom size e2 size 1k bytes 512 bytes end address e2 end 0x03ff 0x01ff
19 7766f?avr?11/10 atmega16/32u4 ?memory programming? on page 346 contains a detailed description on flash data serial down- loading using the spi pins or the jtag interface. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory instruction description and elpm - extended load program memory instruction description). timing diagrams for instruction fetch and execution are presented in ?instruction execution tim- ing? on page 14 . figure 5-1. program memory map 5.2 sram data memory figure 5-2 shows how the atmega16u4/atmega32u4 sram memory is organized. the atmega16u4/atmega32u4 is a complex microcont roller with more peripheral units than can be supported within the 64 location reserved in the opcode for the in and out instructions. for the extended i/o space from $060 - $0ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the first 2,816 data memory locations address both the register file, the i/o memory, extended i/o memory, and the internal data sr am. the first 32 locations address the register file, the next 64 location the standard i/o memory, then 160 locations of extended i/o memory and the next 2,560 locations address the internal data sram. the five different addressing modes for the data memory cover: direct, indirect with displace- ment, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. 0x00000 program memory application flash section boot flash section 0x7fff (32kbytes)
20 7766f?avr?11/10 atmega16/32u4 the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post-incre- ment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, and the 1.25/2.5kbytes of internal data sram in the atmega16u4/atmega32u4 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 12 . figure 5-2. data memory map 5.2.1 data memory access times this section describes the general access timi ng concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 5-3 . figure 5-3. on-chip data sram access cycles 32 r eg i st e r s 64 i/o r eg i st e r s i n t e r na l s r a m $0000 - $001 f $0020 - $005 f $ ffff $0060 - $00 ff d a t a m e m o r y 160 e xt i/o r eg . isram end : $05ff / $0aff isram start : $0100 clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
21 7766f?avr?11/10 atmega16/32u4 5.3 eeprom data memory the atmega16u4/at mega32u4 contains 512by tes/1k bytes of data eeprom memory. it is organized as a separate data space, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the follow ing, specifying the eeprom address regis- ters, the eeprom data register, and the eeprom control register. for a detailed description of spi, jtag and parallel data downloading to the eeprom, see page 360 , page 365 , and page 349 respectively. 5.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 5-3 . a self-timing function, however, lets the user software detect when the next byte can be written. if the user code contains instruc- tions that write the eeprom, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on po wer-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom co rruption? on page 25. for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be followed. refer to the description of the eeprom control regist er for details on this. when the eeprom is read, the cpu is halted for fo ur clock cycles before the next in struction is executed. when the eeprom is written, the cp u is halted for two clock cycles before the next instruction is executed. 5.3.2 the eeprom address register ? eearh and eearl ? bits 15..12 ? res: reserved bits these bits are reserved bits in the atmega 16u4/atmega32u4 and will always read as zero. ? bits 11..0 ? eear8..0: eeprom address the eeprom address registers ? eearh and eearl specify the eeprom address in the 512bytes/1k bytes eeprom space. the eepr om data bytes are addressed linearly between 0 and e2_end. the initial value of eear is und efined. a proper value must be written before the eeprom may be accessed. 5.3.3 the eeprom data register ? eedr bit 1514131211 10 9 8 ????eear11eear10eear9eear8eearh eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 76543 2 10 read/writerrrrr/wr/wr/wr/w r/w r/w r/w r/w r/w r/w r/w r/w initial value0000x x xx xxxxx x xx bit 76543210 msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
22 7766f?avr?11/10 atmega16/32u4 ? bits 7..0 ? eedr7.0: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address given by the eear regi ster. for the eeprom read operation, the eedr contains the data read out from the eeprom at the add ress given by eear. 5.3.4 the eeprom control register ? eecr ? bits 7..6 ? res: reserved bits these bits are reserved bits in the atmega 16u4/atmega32u4 and will always read as zero. ? bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bit setting define s which programming acti on that will be trig- gered when writing eepe. it is possible to program data in one atomic operation (erase the old value and program the new value) or to split the erase and write operations in two different operations. the programming times for the different modes are shown in table 5-2 . while eepe is set, any write to eepmn will be ignored. du ring reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i bit in sreg is set. writing eerie to zero disables the interrupt. the eeprom ready interrupt generates a constant inter- rupt when eepe is cleared. ? bit 2 ? eempe: eeprom master programming enable the eempe bit determines whether setting eepe to one causes the eeprom to be written. when eempe is set, setting eepe within four cloc k cycles will write data to the eeprom at the selected address if eempe is zero, setting eepe will have no effect. when eempe has been written to one by software, ha rdware clears the bit to zero after four clock cycles. see the description of the eepe bit fo r an eeprom write procedure. ? bit 1 ? eepe: eeprom programming enable the eeprom write enable signal eepe is the wr ite strobe to the eeprom. when address and data are correctly set up, the eepe bit must be written to one to write the value into the eeprom. the eempe bit must be written to one be fore a logical one is written to eepe, other- bit 765432 10 ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0 table 5-2. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4 ms erase and write in one operation (atomic operation) 0 1 1.8 ms erase only 1 0 1.8 ms write only 1 1 ? reserved for future use
23 7766f?avr?11/10 atmega16/32u4 wise no eeprom write takes pl ace. the following pr ocedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. wait until eepe becomes zero. 2. wait until selfprgen in spmcsr becomes zero. 3. write new eeprom address to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eempe bit while writing a zero to eepe in eecr. 6. within four clock cycles after sett ing eempe, write a logical one to eepe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is co mpleted before initiating a new eeprom write. step 2 is only relevant if the software contai ns a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see ?memory pro- gramming? on page 346 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an interrupt routine accessing the eeprom is interrupting another eeprom acce ss, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. when the write access time has elapsed, the ee pe bit is cleared by hardware. the user soft- ware can poll this bit and wait for a zero before writing the next byte. when eepe has been set, the cpu is halted for two cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the re ad strobe to the eeprom. when the correct address is set up in the eear register, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and th e requested data is available immediately. when t he eeprom is read, the cpu is ha lted for four cycles before the next instruction is executed. the user should poll the eepe bit before starting the read operation. if a write operation is in progress, it is neither possi ble to read the eeprom, nor to change the eear register. the calibrated oscillator is used to time the eeprom accesses. table 5-3 lists the typical pro- gramming time for eeprom access from the cpu. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (e.g. by dis abling interrupts glob- ally) so that no interrupts will occur during ex ecution of these functions. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait fo r any ongoing spm co mmand to finish. table 5-3. eeprom programming time symbol number of calibrated rc oscillator cycles typ programming time eeprom write (from cpu) 26,368 3.3 ms
24 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. the next code examples show assembly and c functions for reading the eeprom. the exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. assembly code example (1) eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eempe sbi eecr,eempe ; start eeprom write by setting eepe sbi eecr,eepe ret c code example (1) void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 25 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. 5.3.5 preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupted because the supply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eepr om, and the same design so lutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. sec- ondly, the cpu itself can execute instructions incorrectly, if the supp ly voltage is too low. eeprom data corruption can ea sily be avoided by followin g this design recommendation: keep the avr reset active (low) during periods of insufficient power su pply voltage. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress , the write operation will be com- pleted provided that the power supply voltage is sufficient. assembly code example (1) eeprom_read: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example (1) unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 26 7766f?avr?11/10 atmega16/32u4 5.4 i/o memory the i/o space definition of the atmega16u4/atmega32u4 is shown in ?register summary? on page 408 . all atmega16u4/atmega32u4 i/os and peripherals are placed in the i/o space. all i/o loca- tions may be accessed by the ld/lds/ldd and st /sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-acce ssible using the sbi an d cbi instructions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega16u4/atmega32u4 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instruc- tions can be used. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avrs, the cbi and sbi instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work with reg- isters 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. 5.4.1 general purpose i/o registers the atmega16u4/atmega32u4 contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for storing global vari- ables and status flags. general purpose i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. 5.4.2 general purpose i/o register 2 ? gpior2 5.4.3 general purpose i/o register 1 ? gpior1 5.4.4 general purpose i/o register 0 ? gpior0 bit 76543210 msb lsb gpior2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb gpior1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb gpior0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
27 7766f?avr?11/10 atmega16/32u4 6. system clock and clock options 6.1 clock systems and their distribution figure 6-1 presents the principal clock systems in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ?power manage- ment and sleep modes? on page 43 . the clock systems are detailed below. figure 6-1. clock distribution 6.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. examples of such modules are the general pur pose register file, the status register and the data memory holding the stack pointer. halting the cpu clock inhibits the core from performing general operations and calculations. 6.1.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, spi, and usart. the i/o clock is also used by the external inte rrupt module, but note that some external inter- rupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also, twi address recognition is handled in all sleep modes. 6.1.3 flash clock ? clk flash the flash clock controls operation of the flash in terface. the flash clock is usually active simul- taneously with the cpu clock. general i/o modules cpu core ram clk i/o avr clock control unit clk cpu flash and eeprom clk flash source clock watchdog timer reset logic clock multiplexer watchdog clock calibrated rc oscillator crystal oscillator external clock adc clk adc system clock prescaler watchdog oscillator usb clk usb (48mhz) pll clock prescaler pll clk pllpresc high speed timer clk pll pll postcaler (1) (2) clk tmr pll input multiplexer clock switch
28 7766f?avr?11/10 atmega16/32u4 6.1.4 adc clock ? clk adc the adc is provided with a dedicated clock domain. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this gives more accurate adc conversion results. 6.1.5 pll prescaler clock ? clk pllpresc the pll requires a 8 mhz input. a prescaler allows user to use either a 8mhz or a 16mhz source (from a crystal or an external source), using a divider (by 2) if necessary. the output of the prescaler goes into the pll input multiplexer, that allows the user to select either the pres- caler output of the syst em clock multiplexer, or the in ternal 8mhz calibrated oscillator. 6.1.6 pll output clock ? clk pll when enabled, the pll outputs one frequency among numerous choices between 32mhz and 96 mhz. the output frequency is determined by the pll clock register. the frequency is inde- pendent of the power supply voltage. the pll output is connected to a postcaler that allows user to generate two different frequencies (clk usb and clk tmr ) from the common pll signal, each on them resulting of a selected division ratio (/1, /1.5, /2). 6.1.7 high-speed timer clock? clk tmr when enabled, the pll outputs one frequency among numerous choices between 32mhz and 96 mhz, that goes into the pll postcaler. the high speed timer frequency input is generated from the pll postcaler, that proposes /1, /1.5 and /2 ratios. that can be determined from the pll clock register. the high speed timer maximum frequency input depends on the power sup- ply voltage and reaches its maximum of 64 mhz at 5v. 6.1.8 usb clock ? clk usb the usb hardware module needs for a 48 mhz cloc k. this clock is generated from the on-chip pll. the output of the pll passes through the pll postcaler where the frequency can be either divided by 2 or directly connected to the clk usb signal. 6.2 clock sources the device has the following clock source options, selectable by flash fuse bits as shown below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. table 6-1. device clocking options select (1) device clocking option cksel[3:0] (or excksel[3:0]) low power crystal oscillator 1111 - 1000 reserved 0111 - 0110 low frequency crystal oscillator 0101 - 0100 reserved 0011 calibrated internal rc oscillator 0010 external clock 0000 reserved 0001
29 7766f?avr?11/10 atmega16/32u4 6.2.1 default clock source atmega16u4 and atmega32u4 the device is shipped with low power crystal oscilla tor (8.0mhz-16mhz) en abled and with the fuse ckdiv8 programmed, resulting in 1.0mhz system clock with an 8 mhz crystal. see table 28-5 on page 348 for an overview of the default clock selection fuse setting. 6.2.2 default clock source atmega16u4rc and atmega32u4rc the device is shipped with calib rated internal rc osc illator (8.0mhz) enabled and with the fuse ckdiv8 programmed, resulting in 1.0mhz system clock. see table 28-5 on page 348 for an overview of the default clock selection fuse setting. 6.2.3 clock startup sequence any clock source needs a sufficient v cc to start oscillating and a minimum number of oscillating cycles before it can be considered stable. to ensure sufficient v cc , the device issues an internal reset with a time-out delay (t tout ) after the device reset is released by all other reset sources. ?on-chip debug system? on page 48 describes the start conditions for the internal reset. the delay (t tout ) is timed from the watchdog oscillator and the number of cycles in the delay is set by the sutx and ckselx fuse bits. the selectable delays are shown in table 6-2 . the frequency of the watchdog oscillator is voltage dependent as shown in table 6-2 . main purpose of the delay is to keep the avr in reset until it is supplied with minimum vcc. the delay will not monitor t he actual voltage and it w ill be required to select a delay longer than the vcc rise time. if this is not possible, an intern al or external brown-out detection circuit should be used. a bod circuit will ensure sufficient vcc before it releases the reset, and the time -out delay can be disabled. disabling the time-out delay wi thout utilizing a brown-out detection circuit is not recommended. the oscillator is required to oscillate for a minimu m number of cycles befo re the clock is consid- ered stable. an inte rnal ripple counter monito rs the oscillator output cl ock, and keep s the internal reset active for a given number of clock cycl es. the reset is then released and the device will start to execute. the recommend ed oscillator start-up time is dependent on the clock type, and varies from 6 cycles for an externally applied clock to 32k cycles for a low frequency crystal. the start-up sequence for the clock includes both the time-out delay and the start-up time when the device starts up from reset. when starting up from power-save or power-down mode, vcc is assumed to be at a sufficient level and only the start-up time is included. 6.3 low power crystal oscillator pins xtal1 and xtal2 are input and output, respec tively, of an invertin g amplifier which can be configured for use as an on-c hip oscillator, as shown in figure 6-2 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a low power oscillator, with reduced voltage swing on the xtal2 out- put. it gives the lowest power consumption, but is not capable of driving other clock inputs. table 6-2. number of watchdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 0 ms 0 ms 0 4.1 ms 4.3 ms 512 65 ms 69 ms 8k (8,192)
30 7766f?avr?11/10 atmega16/32u4 c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 6-3 . for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 6-2. crystal oscillator connections the low power oscillator c an operate in three diff erent modes, each optimi zed for a specific fre- quency range. the operating mode is selected by the fuses cksel[3..1] as shown in table 6-3 . notes: 1. the frequency ranges are preliminary values. actual values are tbd. 2. this option should not be used with crystals, only with ceramic resonators. 3. if 8 mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets th e frequency specification of the device. the cksel0 fuse together with the sut1..0 fuses select the start-up times as shown in table 6-4 . table 6-3. low power crystal osc illator operating modes (3) frequency range (1) (mhz) cksel3..1 recommended range for capacitors c1 and c2 (pf) 0.4 - 0.9 100 (2) ? 0.9 - 3.0 101 12 - 22 3.0 - 8.0 110 12 - 22 8.0 - 16.0 111 12 - 22 table 6-4. start-up times for the low power cr ystal oscillator clock selection oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 ceramic resonator, fast rising power 258 ck 14ck + 4.1 ms (1) 000 ceramic resonator, slowly rising power 258 ck 14ck + 65 ms (1) 001 ceramic resonator, bod enabled 1k ck 14ck (2) 010 ceramic resonator, fast rising power 1k ck 14ck + 4.1 ms (2) 011 xtal2 xtal1 gnd c2 c1
31 7766f?avr?11/10 atmega16/32u4 notes: 1. these options should only be used when not operating close to the maximum frequency of the device, and only if frequency stability at start- up is not important for the application. these options are not suitable for crystals. 2. these options are intended for use with cerami c resonators and will ensure frequency stability at start-up. they can also be used with crystal s when not operating close to the maximum fre- quency of the device, and if frequency stability at start-up is not important for the application. note: 1. the device is shipped wit h this option selected. 6.4 low frequency crystal oscillator the device can utilize a 32.768 khz watch crystal as clock source by a dedicated low fre- quency crystal oscillator. the crystal should be connected as shown in figure 6-2 . when this oscillator is selected, start-up times are determi ned by the sut fuses and cksel0 as shown in table 6-6 . ceramic resonator, slowly rising power 1k ck 14ck + 65 ms (2) 100 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1 ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65 ms 1 11 table 6-5. start-up times for the internal calib rated rc oscillator clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1 ms 01 slowly rising power 6 ck 14ck + 65 ms (1) 10 reserved 11 table 6-4. start-up times for the low power crysta l oscillator clock se lection (continued) oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 table 6-6. start-up times for the lo w frequency crystal oscillator clock selection power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 bod enabled 1k ck 14ck (1) 000 fast rising power 1k ck 14ck + 4.1 ms (1) 001 slowly rising power 1k ck 14ck + 65 ms (1) 010 reserved 0 11 bod enabled 32k ck 14ck 1 00 fast rising power 32k ck 14ck + 4.1 ms 1 01 slowly rising power 32k ck 14ck + 65 ms 1 10 reserved 1 11
32 7766f?avr?11/10 atmega16/32u4 note: 1. these options should only be used if frequen cy stability at start-up is not important for the application. 6.5 calibrated internal rc oscillator the calibrated internal rc osc illator by default prov ides a 8.0 mhz cloc k. this frequency is nominal value at 3v and 25 c. the device is shipped with the ckdiv8 fuse programmed. see ?system clock prescaler? on page 37 for more details. this clock may be selected as the system clock by programming the cksel fuses as shown in table 6-7 . if selected, it will operate with no external components. during reset, hardware loads the calibration byte into the osccal register and thereb y automatically calibrates the rc oscillator. at 3v and 25 c, this calibration gives a frequency of 8 mhz 1%. the oscillator can be calibrated to an y frequency in the range 7.3 - 8.1 mhz within 1% accuracy, by changing the osccal register. when this oscillator is used as the chip clock, the wa tchdog oscillator will still be used for the watchdog timer and for the reset time-out. for more information on the pre-programmed calibration value, see the sec- tion ?calibration byte? on page 349 notes: 1. the device is shipped with this option selected. 2. the frequency ranges are preliminary values. actual values are tbd. 3. if 8 mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. when this oscillator is select ed, start-up times are determined by the sut fuses as shown in table 6-5 on page 31 . 6.5.1 oscillator calibra tion register ? osccal ? bits 7..0 ? cal7..0: oscillator calibration value the oscillator calibration register is used to trim the calibrated internal rc oscillator to remove process variations from the oscillator frequency . the factory-calibrate d value is automat- ically written to this r egister during chip reset, giving an oscillator frequen cy of 8.0 mhz at 25c. the application software can write this register to change the oscillator frequency. the calibra- tion range is +/- 40% and linear (calibration step ~0.4%). with typical process at 25c the code should be 127 for 8 mhz. input value of 0x00 gives the lowest frequency, and 0xff the highest. table 6-7. internal calibrated rc o scillator operating modes (1)(3) frequency range (2) (mhz) cksel[3:0] 7.3 - 8.1 0010 table 6-8. start-up times for the internal calib rated rc oscillator clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1 ms 01 slowly rising power 6 ck 14ck + 65 ms 10 reserved 11 bit 76543210 cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device spec ific calibration value
33 7766f?avr?11/10 atmega16/32u4 the temperature sensitivity is quite linear but as said previously depends on the process. to determine its slope, the frequency must be measured at two temperatures. the temperature sensor of the atmega16u4/atmega32u4 allows such an operation, that is detailed on section 24.6.1 ?sensor calibration? on page 300 . it is then possible to calibrate the oscillator frequency in function of the temperature measured. note that this o scillator is used to time eeprom and flash write accesses , and these write times will be affected accordingly. if the eeprom or flash are writ ten, do not calibrate to more than 8.8 mhz. other wise, the eeprom or flash write may fail. 6.5.2 oscillator cont rol register ? rcctrl bits 7..1 ? reserved do not set these bits. bits should be read as ?0?. bit 0? rcfreq: rc oscill ator frequency select when this bit is cleared (default value), the rc oscillator output frequency is set to 8 mhz. when the bit is set, the rc output frequency is 1 mhz. note that the osccal value has the same effect on both 8 mhz and 1 mhz output modes (~0.4% / step). 6.6 external clock the device can utilize a external clock source as shown in figure 6-3 . to run the device on an external clock, the c ksel fuses must be pr ogrammed as shown in table 6-1 . figure 6-3. external clock drive configuration when this clock source is sele cted, start-up times are determined by the sut fuses as shown in table 6-9 . bit 76543210 -------rcfreq rcctrl read/writerrrrrrrr/w initial value00000000 nc external clock signal xtal2 xtal1 gnd
34 7766f?avr?11/10 atmega16/32u4 when applying an external clock, it is required to avoid sudden changes in the applied clock fre- quency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredict able behavior. if changes of more than 2% is required, ensure that the mcu is kept in reset during the changes. note that the system clock prescaler can be used to implement run-time changes of the internal clock frequency while still ensuri ng stable operation. refer to ?system clock prescaler? on page 37 for details. 6.7 clock switch the atmega16u4/atmega32u4 product includes a clo ck switch controller, that allows user to switch from one clock source to another one by software, in order to control application power and execution time with more accuracy. 6.7.1 example of use the modification may be needed when the device enters in usb suspend mode. it then switches from external clock to calibrated rc oscillator in order to reduce consumption and wake-up delay. in such a configuration, the ex ternal clock is disabl ed. the firmware can then use the watchdog timer to be woken-up from power-down in order to check if there is an event on the application. if an event occurs on the application or if the usb controller signals a non- idle state on the usb line (resume for example) , the firmware switches the clock multiplexer from the calibrated rc oscillator to the external clock. in or der to restart usb operation. this feature can only be used to switch between calibrated 8 mh z rc oscillator, external clock and low power crystal oscillator. the low freq uency crystal oscillator must not be used with this feature. table 6-9. start-up times for the external clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1 ms 01 slowly rising power 6 ck 14ck + 65 ms 10 reserved 11
35 7766f?avr?11/10 atmega16/32u4 figure 6-4. example of clock switching with wake-up from usb host figure 6-5. example of clock switching with wake-up from device 6.8 clock switch algorithm 6.8.1 switch from external clock to rc clock if (usb_suspend_detected()) // if (udint.suspi == 1) { usb_ack_suspend(); // udint.suspi = 0; usb_freeze_clock(); // usbcon.frzclk = 1; disable_pll(); // pllcsr.plle = 0; enable_rc_clock(); // clksel0.rce = 1; while (!rc_clock_ready()); // while (clksta.rcon != 1); select_rc_clock(); // clksel0.clks = 0; disable_external_clock(); // clksel0.exte = 0; } usb cpu clock exte rn al oscillator rc oscillator ext rc ext non-idle idle (suspend) non-idle 3m s resume 1 1 resume from host w atchdog wake-up from power-down usb cpu clock exte rn al oscillator rc oscillator ext rc ext non-idle idle (suspend) non-idle 3m s upstream-resume 2 2 upstream resume from device w atchdog wake-up from power-down
36 7766f?avr?11/10 atmega16/32u4 6.8.2 switch from rc clock to external clock if (usb_wake_up_detected()) // if (udint.wakeupi == 1) { usb_ack_wake_up(); // udint.wakeupi = 0; enable_external_clock(); // cksel0.exte = 1; while (!external_clock_ready()); // while (clksta.exton != 1); select_external_clock(); // clksel0.clks = 1; enable_pll(); // pllcsr.plle = 1; disable_rc_clock(); // clksel0.rce = 0; while (!pll_ready()); // while (pllcsr.plock != 1); usb_unfreeze_clock(); // usbcon.frzclk = 0; } 6.8.3 clksel0 ? clock selection register 0 ? bit 7-6 ? rcsut[1:0]: sut for rc oscillator these 2 bits are the sut value for the rc oscillator. if the rc oscilla tor is selected by fuse bits, the sut fuse are copied into th ese bits. a firmware change will not have any effect because this additional start-up time is only used after a reset and not after a clock switch. ? bit 5-4 ? exsut[1:0]: sut for external clock/ low power crystal oscillator these 2 bits are the sut value for the external clock / low power crystal oscillator. if the external clock / low power crystal oscillator is selected by fuse bits, the sut fuses are copied into these bits. the firmware can modify these bits by writing a new value. this value will be used at the next start of the external clock / low power crystal oscillator. ? bit 3 ? rce: enable rc oscillator the rce bit must be written to logic one to en able the rc oscillator. the rce bit must be writ- ten to logic zero to di sable the rc oscillator. ? bit 2 ? exte: enable external clock / low power crystal oscillator the osce bit must be written to logic one to enable external cl ock / low power crystal oscilla- tor. the osce bit must be written to logic zero to disable the external clock / low power crystal oscillator. ? bit 0 ? clks: clock selector the clks bit must be written to logic one to select the external clock / low power crystal oscil- lator as cpu clock. the clks bit must be writt en to logic zero to select the rc oscillator as cpu clock. after a reset, the clks bit is set by ha rdware if the external clock / low power crys- tal oscillator is selected by the fuse bits configuration. the firmware has to check if the clock is correctly started before selected it. 6.8.4 clksel1 ? clock selection register 1 bit 7 6 5 4 3210 rcsut1 rcsut0 exsut1 exsut0 rce exte - clks clksel0 read/write r/w r/w r/w r/w r/w r/w r r/w initial value 0 0 0 0 see bit description bit 7 6543210 rccks el3 rccks el2 rccks el1 rccks el0 excks el3 excks el2 excks el1 excks el0 clksel1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 1 0 0 0 0 0
37 7766f?avr?11/10 atmega16/32u4 ? bit 7-4 ? rccksel[3:0]: cksel for rc oscillator clock configuration for the rc oscillator. after a re set, this part of the re gister is loaded with the 0010b value that corres ponds to the rc oscillator. modifyin g this value by firmware before switching to rc oscillator is prohibit ed because the rc clock will not start. ? bit 3-0 ? excksel[3:0]: cksel for external clock / low power crystal oscillator clock configuration for the external clock / low power crystal oscillator. after a reset, if the external clock / low power crystal oscillator is sele cted by fuse bits, this part of the register is loaded with the fuse configuration. firmware can modify it to change the start-up time after the clock switch. see ?device clocking options select(1)? on page 28 for excksel[3:0] configuration. only low power crystal oscillator, calibrated internal rc oscillator, and external clock modes are allowed. 6.8.5 clksta ? clock status register ? bit 7-2 - reserved bits these bits are reserved and will always read as zero. ? bit 1 ? rcon: rc oscillator on this bit is set by hardware to one if the rc oscillator is running. this bit is set by hardware to ze ro if the rc oscillator is stopped. ? bit 0 ? exton: external clock / low power crystal oscillator on this bit is set by hardware to one if the external clock / low po wer crystal oscillator is running. this bit is set by hardware to zero if the external clock / low power crystal oscillator is stopped. 6.9 clock output buffer the device can output the system clock on t he clko pin. to enable the output, the ckout fuse has to be programmed. this mode is suitable when the chip clock is used to drive other cir- cuits on the system. the clock also will be output during reset, and the normal operation of i/o pin will be overridden when the fu se is programmed. an y clock source, includi ng the internal rc oscillator, can be selected when the clock is output on clko. if the system clock prescaler is used, it is the divided system clock that is output . 6.9.1 system clock prescaler the avr usb has a system clock prescaler, and the system clock can be divided by setting the ?clkpr ? clock prescaler register? on page 38 . this feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. this can be used with all clock source options, and it will affect the clock frequency of the cpu and all synchronous peripherals. clk i/o , clk adc , clk cpu , and clk flash are divided by a factor as shown in table 6-10 . when switching between prescaler settings, the system clock prescaler ensures that no glitches occurs in the clock system. it also ensures that no intermediate frequency is higher than neither the clock frequency corresponding to the previous setting, nor the clock frequency corre- sponding to the new setting. bit 7 6543210 - - - - - - rcon exton clksta read/write r r r r r r r r initial value 0 0 0 0 0
38 7766f?avr?11/10 atmega16/32u4 the ripple counter that implements the prescaler runs at the frequency of the undivided clock, which may be faster than the cpu's clock frequency. hence, it is not possible to determine the state of the prescaler - even if it were readable, and the exact time it takes to switch from one clock division to the other cann ot be exactly predicted. from th e time the clkps values are writ- ten, it takes between t1 + t2 and t1 + 2 * t2 before the new clock frequency is active. in this interval, 2 active clock edges are produced. here, t1 is the previous clock period, and t2 is the period corresponding to the new prescaler setting. to avoid unintentional changes of clock frequency, a special write procedure must be followed to change the clkps bits: 1. write the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. 2. within four cycles, write the desired va lue to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted. 6.9.2 clkpr ? clock prescaler register ? bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enab le change of the clkps bits. the clkpce bit is only updated when the other bits in cl kpr are simultaneously wr itten to zero. clkpce is cleared by hardware four cycles af ter it is written or when clkps bits are written. rewriting the clkpce bit within this time-out period does neither extend the time-out period, nor clear the clkpce bit. ? bits 3..0 ? clkps[3..0]: clock prescaler select bits 3 - 0 these bits define the division factor between the selected clock source and the internal system clock. these bits can be written run-time to vary the clock frequency to suit the application requirements. as the divider divides the master clock input to the mcu, the speed of all synchro- nous peripherals is reduced when a division fact or is used. the division factors are given in table 6-10 . the ckdiv8 fuse determines the initial value of the clkps bits. if ckdiv8 is unprogrammed, the clkps bits will be reset to ?0000?. if ckdiv8 is programmed, clkps bits are reset to ?0011?, giving a division factor of 8 at start up. this feature should be used if the selected clock source has a higher frequency than the maximum frequency of the device at the present operat- ing conditions. note that any value can be written to the clkps bits regardless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is chosen if bit 7 6543210 clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 see bit description
39 7766f?avr?11/10 atmega16/32u4 the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. the device is shipped with the ckdiv8 fuse programmed. 6.10 pll the pll is used to generate internal high fr equency (up to 96mhz) clock for usb interface and/or high speed timer module, the pll input is supplied from an external low-frequency clock (the crystal oscillator or exte rnal clock input pin from xtal1). 6.10.1 internal pll the internal pll in atmega16u4/atmega32u4 generates a clock frequency between 32mhz and 96 mhz from nominally 8mhz input. the source of the 8mhz pll input clock is the output of the internal pll clock prescaler that generates the 8mhz from the clock source multiplexer output (see section 6.10.2 for pll inter- face). the pll prescaler allows a direct connection (8mhz oscillato r) or a divide-by-2 stage for a 16mhz clock input. the pll output signal enters the pll postcaler stage before being distributed to the usb and high speed timer modules. each of these modules can choose an independent division ratio. table 6-10. clock prescaler select clkps3 clkps2 clk ps1 clkps0 clock division factor 0000 1 0001 2 0010 4 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 1001 reserved 1010 reserved 1011 reserved 1100 reserved 1101 reserved 1110 reserved 1111 reserved
40 7766f?avr?11/10 atmega16/32u4 figure 6-6. pll clocking system 6.10.2 pll control and status register ? pllcsr ? bit 7..5 ? res: reserved bits these bits are reserved bits in the atmega16u4/atmega32u4 and always read as zero. ? bit 4 ? pindiv pll input prescaler (1:1, 1:2) these bits allow to configure the pll input prescaler to generate the 8mhz input clock for the pll from either a 8 or 16 mhz input. when using a 8 mhz clock source, this bit must be set to 0 before enabling pll (1:1). when using a 16 mhz clock source, this bit must be set to 1 before enabling pll (1:2). ? bit 3..2 ? res: reserved bits these bits are reserved bits in the atmega16u4/atmega32u4 and always read as zero. ? bit 1 ? plle: pll enable when the plle is set, the pll is started. note that the calibrated 8 mhz internal rc oscillator is automatically enabled when the plle bit is set and with pinmux (see pllfrq register) is set. the pll must be disabled before entering power down mode in order to stop internal rc oscil- lator and avoid extra-consumption. ? bit 0 ? plock: pll lock detector when the plock bit is set, the pll is locked to the reference clock. after the pll is enabled, it takes about several ms for the pll to lock. to clear plock, clear plle. 6.10.3 pll frequency control register ? pllfrq 8 mhz rc oscillator xtal1 xtal2 xtal oscillator pll plle lock detector clk tmr to system clock prescaler clk 8mhz pll clock prescaler pindiv pdiv3..0 clk usb /2 /1.5 plltm1:0 pllusb 0 1 pinmux 0 1 01 10 11 cksel3:0 plock bit 76543210 $29 ($29) pindiv plle plock pllcsr read/write r r r r/w r r r/w r initial value 0 0 0 0 0 0 0 0 bit 76543210 $32 pinmux pllusb plltm1 plltm0 pdiv3 pdiv2 pdiv1 pdiv0 pllfrq read/writer/wr/wr/wr/wr/wr/wr/wr/w initial value 0 0 0 0 0 1 0 0
41 7766f?avr?11/10 atmega16/32u4 ? bit 7? pinmux: pll input multiplexer this bit selects the clock input of the pll: ? pinmux = 0: the pll input is connected to the pll prescaler, that has the primary system clock as source ? pinmux = 1: the pll input is directly connected to the internal calibrated 8mhz rc oscillator. this mode allo ws to work in usb low speed mode with no crystal or using a crystal with a value different of 8/16mhz. ? bit 6? pllusb: pll postcaler for usb peripheral this bit select the division factor between the pll output frequency and the usb module input frequency: ? pllusb = 0: no division, direct connection (if pll output = 48 mhz) ? pllusb = 1: pll output frequency is divided by 2 and sent to usb module (if pll output = 96mhz) ? bit 5..4 ? plltm1:0: pll postcaler for high speed timer these bits codes for the division factor betw een the pll output frequency and the high speed timer input frequency. note that the division factor 1.5 will introduce some jitter in t he clock, but keeping the error null since the average duty cycle is 50%. see figure 6-7 for more details. figure 6-7. pll postcaler operation with division factor = 1.5 ? bit 3..0 ? pdiv3:0 pll lock frequency these bits configure the pll internal vco clock reference according to the required output fre- quency value. plltm1 plltm0 pll postcaler fa ctor for high-speed timer 0 0 0 (disconnected) 01 1 10 1.5 11 2 pdiv3 pdiv2 pdiv1 pdiv0 pl l output frequency 0 0 0 0 not allowed 0 0 0 1 not allowed 0 0 1 0 not allowed 0011 40 mhz 0100 48 mhz f i f i x --- 2 3
42 7766f?avr?11/10 atmega16/32u4 the optimal pll configuration at 5v is: pll outp ut frequency = 96 mhz, divided by 1.5 to gener- ate the 64 mhz high speed timer clock, and divided by 2 to generate the 48 mhz usb clock. 0101 56 mhz 0 1 1 0 not allowed 0111 72 mhz 1000 80 mhz 1001 88 mhz 1010 96 mhz 1 0 1 1 not allowed 1 1 0 0 not allowed 1 1 0 1 not allowed 1 1 1 0 not allowed 1 1 1 1 not allowed pdiv3 pdiv2 pdiv1 pdiv0 pl l output frequency
43 7766f?avr?11/10 atmega16/32u4 7. power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consump- tion to the application?s requirements. to enter any of the five sleep modes, the se bit in smcr must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the smcr register select which sleep mode (idle, adc noise reduction, power-down, power-save, or standby) will be activated by the sleep instruction. see table 7-1 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then ha lted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following sleep. the contents of the register file and sram are unaltered when the device wakes up from sleep. if a reset oc curs during sleep mode, the mcu wakes up and executes from the reset vector. figure 6-1 on page 27 presents the different clock systems in the atmega16u4/atmega32u4, and their distribution. the figure is helpful in selecting an appropriate sleep mode. 7.0.1 sleep mode control register ? smcr the sleep mode control register contains control bits for power management. ? bits 3, 2, 1 ? sm2..0: sleep mode select bits 2, 1, and 0 these bits select between the six available sleep modes as shown in table 7-1 . note: 1. standby modes are only recommended for use with external crystals or resonators. ? bit 1 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu enteri ng the sleep mode unless it is the programmer?s purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instruction and to clear it immediately af ter waking up. bit 76543210 ????sm2sm1sm0sesmcr read/writerrrrr/wr/wr/wr/w initial value00000000 table 7-1. sleep mode select sm2 sm1 sm0 sleep mode 000idle 0 0 1 adc noise reduction 010power-down 011power-save 100reserved 101reserved 110standby (1) 1 1 1 extended standby (1)
44 7766f?avr?11/10 atmega16/32u4 7.1 idle mode when the sm2..0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing the usb, spi, usart, analog comparator, adc, 2-wire serial interface, timer/counters , watchdog, and the interrupt syst em to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the timer overflow and usart transmit complete interrupts. if wake-up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the acd bit in the analog comparator control and status regist er ? acsr. this will reduce power consumption in idle mode. if t he adc is enabled, a conversion starts automati- cally when this mode is entered. 7.2 adc noise reduction mode when the sm2..0 bits are written to 001, the sleep instruction makes the mcu enter adc noise reduction mode, stopping the cpu but allowi ng the adc, the external interrupts, 2-wire serial interface address match and the watchdog to continue operating (if enabled). this sleep mode basically halts clki/o, clkc pu, and clkflash, while allo wing the other clocks to run (including clkusb). this improves the noise environment for the ad c, enabling higher resolution measurements. if the adc is enabled, a conversion starts automatically when this mode is entered. apart form the adc conversion complete inte rrupt, only an external reset, a watchdog system reset, a watchdog interrupt, a brown-out reset, a 2-wire serial interface interrupt, an spm/eeprom ready interrupt, an external level interrupt on int6, an external interrupt on int3:0 or a pin change interrupt can wake up the mcu from adc noise reduction mode. 7.3 power-down mode when the sm2..0 bits are written to 010, the sleep instruction makes the mcu enter power- down mode. in this mode, the external osc illator is stopped, while the external interrupts, the 2- wire serial interface, and the watchdog continue operating (if enabled). only an external reset, a watchdog reset, a brown-out reset, 2-wire serial interface address match, an external level interrupt on int6, an external interrupt on int3:0, a pin change interrupt or an asynchronous usb interrupt sources (vbusti, wakeupi), can wake up the mcu. this sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external interrupts? on page 85 for details. when waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 28 . 7.4 power-save mode when the sm2..0 bits are written to 011, the sleep instruction makes the mcu enter power- save mode. for compatibility reasons with at90us b64/128 this mode is still present but since timer 2 asynchronous operation is not present here, this mode is id entical to power-down.
45 7766f?avr?11/10 atmega16/32u4 7.5 standby mode when the sm2..0 bits are 110 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. fr om standby mode, the device wakes up in six clock cycles. 7.6 extended standby mode when the sm2..0 bits are 111 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter extende d standby mode. for compatib ility reasons with at90usb64/128 this mode is still present but since timer 2 asynchronous operation is not present here, this mode is identical to standby-mode. notes: 1. only recommended with external crystal or resonator selected as clock source. 2. for int6, only level interrupt. 3. asynchronous usb interrupts are vbusti and wakeupi. 7.7 power reduction register the power reduction register, prr, provides a method to stop the clock to individual peripher- als to reduce power consumption. the current state of the peripheral is frozen and the i/o registers can not be read or written. resources used by the peripheral when stopping the clock will remain occupied, hence the perip heral should in most cases be disabled before stopping the clock. waking up a module, which is done by clear ing the bit in prr, puts the module in the same state as before shutdown. module shutdown can be used in idle mode and ac tive mode to significantly reduce the overall power consumption. in all other sleep modes, the clock is already stopped. table 7-2. active clock domains and wake-up sour ces in the different sleep modes. active clock domains o scillators wake-up sources sleep mode clk cpu clk flash clk io clk adc main clock source enabled int6, int3:0 and pin change twi address match spm/ eeprom ready adc wdt interrupt other i/o usb synchronous interrupts usb asynchronous interrupts (3) idle x x x xxxxxxxx adcnrm x x x (2) xxxx xx power-down x (2) xxx power-save x (2) xxx standby (1) xx (2) xxx extended standby xx (2) xxx
46 7766f?avr?11/10 atmega16/32u4 7.7.1 power reduction register 0 - prr0 ? bit 7 - prtwi: power reduction twi writing a logic one to this bit shuts down the twi by stopping the clock to the module. when waking up the twi again, the twi should be re initialized to ensure proper operation. ? bit 6 - res: reserved bit this bits is reserved and will always read as zero. ? bit 5 - prtim0: power reduction timer/counter0 writing a logic one to this bit shuts down the timer/counter0 module. when the timer/counter0 is enabled, operation will cont inue like before the shutdown. ? bit 4 - res: reserved bit this bit is reserved and will always read as zero. ? bit 3 - prtim1: power reduction timer/counter1 writing a logic one to this bit shuts down the timer/counter1 module. when the timer/counter1 is enabled, operation will cont inue like before the shutdown. ? bit 2 - prspi: power reduction serial peripheral interface writing a logic one to this bit shuts down the seri al peripheral interface by stopping the clock to the module. when waking up the spi again, the spi should be re initialized to ensure proper operation. ? bit 1 - res: reserved bit these bits are reserved and will always read as zero. ? bit 0 - pradc: power reduction adc writing a logic one to this bit shuts down the adc. the adc must be disabled before shut down. the analog comparator cannot use the adc input mux when the adc is shut down. 7.7.2 power reduction register 1 - prr1 ? bit 7 - prusb: power reduction usb writing a logic one to this bit shuts down the usb by stopping the clock to the module. when waking up the usb again, the usb should be re initialized to ensure proper operation. ? bit 6..5 - res: reserved bits these bits are reserved and will always read as zero. bit 7654321 0 prtwi prtim2 prtim0 ? prtim1 prspi - pradc prr0 read/write r/w r/w r/w r r/w r/w r r/w initial value0000000 0 bit 7 654 3 210 prusb ? ? prtim4 prtim3 ? ? prusart1 prr1 read/write r/w r r r r/w r r r/w initial value 0 0 0 0 0 0 0 0
47 7766f?avr?11/10 atmega16/32u4 ? bit 4- prtim4: power reduction timer/counter4 writing a logic one to this bit shuts down the timer/counter4 module. when the timer/counter4 is enabled, operation will cont inue like before the shutdown. ? bit 3 - prtim3: power reduction timer/counter3 writing a logic one to this bit shuts down the timer/counter3 module. when the timer/counter3 is enabled, operation will cont inue like before the shutdown. ? bit 2..1 - res: reserved bits these bits are reserved and will always read as zero. ? bit 0 - prusart1: power reduction usart1 writing a logic one to this bit shuts down the usart1 by stopping the clock to the module. when waking up the usart1 again, the usart1 should be re initialized to ensure proper operation. 7.8 minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possi ble of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consideration when trying to achieve th e lowest possible power consumption. 7.8.1 analog to digital converter if enabled, the adc will be enabled in all sleep modes. to save power, the adc should be dis- abled before entering any sleep mode. when the adc is turned off and on again, the next conversion will be an exte nded conversion. refer to ?analog to digital converter - adc? on page 292 for details on adc operation. 7.8.2 analog comparator when entering idle mode, the analog comparator should be disabled if not used. when entering adc noise reduction mode, the analog comparator should be disabled. in other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. otherwise, the internal voltage reference will be enabled, independent of sleep mode. refer to ?analog comparator? on page 289 for details on how to configure the analog comparator. 7.8.3 brown-out detector if the brown-out detector is not needed by the application, this module should be turned off. if the brown-out detector is enabled by the bo dlevel fuses, it will be enabled in all sleep modes, and hence, always co nsume power. in the deeper sleep modes, this w ill contribute sig- nificantly to the total current consumption. refer to ?brown-out detect ion? on page 52 for details on how to configure the brown-out detector. 7.8.4 internal voltage reference the internal voltage referenc e will be enabled when needed by the brown-out de tection, the analog comparator or the adc. if these modules are disabled as described in the sections above, the internal voltage refe rence will be disabled and it w ill not be consuming power. when
48 7766f?avr?11/10 atmega16/32u4 turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal volt- age reference? on page 54 for details on the start-up time. 7.8.5 watchdog timer if the watchdog timer is not needed in the application, the module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. in the deeper slee p modes, this will contribute signific antly to the total current consump- tion. refer to ?interrupts? on page 61 for details on how to configure the watchdog timer. 7.8.6 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buf fers of the device will be disabled. this ensures that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for detec ting wake-up conditions, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 69 for details on which pins are enabled. if the input buffer is enabl ed and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to v cc /2 on an input pin can cause significant current even in active mode. digital input buffers can be disabled by writing to the digital input disable registers (didr1 and didr0). refer to ?digital input disable register 1 ? didr1? on page 291 and ?digital input dis- able register 1 ? didr1? on page 291 for details. 7.8.7 on-chip debug system if the on-chip debug system is enabled by the ocden fuse and the chip enters sleep mode, the main clock source is enabled, and hence , always consumes power. in the deeper sleep modes, this will contribute significantly to the total cu rrent consumption. there are three alte rnative ways to disable the ocd system: ? disable the ocden fuse. ? disable the jtagen fuse. ? write one to the jtd bit in mcucr.
49 7766f?avr?11/10 atmega16/32u4 8. system control and reset 8.0.1 resetting the avr during reset, all i/o registers are set to their initial values, and the program starts execution from the reset vector. the instruction placed at the reset vector must be a jmp ? absolute jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the app lication section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 8-1 shows the reset logic. table 8-1 defines the electrical parameters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the user through the sut and cksel fuses. the dif- ferent selections for the delay period are presented in ?clock sources? on page 28 . 8.0.2 reset sources the atmega16u4/atmega32u4 has five sources of reset: ? power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ). ? external reset. the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length. ? watchdog reset. the mcu is reset when the watchdog timer period expires and the watchdog is enabled. ? brown-out reset. the mcu is re set when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled. ? jtag avr reset. the mcu is reset as long as there is a logic one in the reset register, one of the scan chains of the jtag system. refer to the section ?ieee 1149.1 (jtag) boundary- scan? on page 320 for details. ? usb end of reset. the mcu is reset (excluding the usb controller that remains enabled and attached) on the detection of a usb end of reset condition on the bus, if this feature is enabled by the user.
50 7766f?avr?11/10 atmega16/32u4 figure 8-1. reset logic notes: 1. the power-on reset will not work un less the supply voltage has been below v pot (falling) 8.0.3 power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detection level is defined in table 8-1 . the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determines how long the table 8-1. reset characteristics symbol parameter condition min typ max units v pot power-on reset threshold voltage (rising) 1.4 2.3 v power-on reset threshold voltage (falling) (1) 1.3 2.3 v v por v cc start voltage to ensure internal power-on reset signal -0.1 +0.1 v v ccrr vcc rise rate to ensure internal power_on reset signal 0.3 v/ms v rst reset pin threshold voltage 0.2 vcc 0.85 vcc v t rst minimum pulse width on reset pin 5v, 25c 400 ns mcu status register (mcusr) brown-out reset circuit bodlevel [2..0] delay counters cksel[3:0] ck timeout wdrf borf extrf porf data bus clock generator spike filter pull-up resistor jtrf jtag reset register watchdog oscillator sut[1:0] power-on reset circuit usb reset detection usbrf
51 7766f?avr?11/10 atmega16/32u4 device is kept in reset after v cc rise. the reset signal is acti vated again, without any delay, when v cc decreases below the detection level. figure 8-2. mcu start-up, reset tied to v cc figure 8-3. mcu start-up, reset extended externally 8.0.4 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see table 8-1 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter starts the mcu after the time-out period ? t tout ? has expired. figure 8-4. external reset during operation v reset time-out internal reset t tout v pot v rst cc v por reset time-out internal reset t tout v pot v rst v cc v por cc
52 7766f?avr?11/10 atmega16/32u4 8.0.5 brown-out detection atmega16u4/atmega32u4 has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the bodlevel fuses. the trigger level has a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. when the bod is enabled, and v cc decreases to a value below the trigger level (v bot- in figure 8-5 ), the brown-out reset is immediately activated. when v cc increases above the trigger level (v bot+ in figure 8-5 ), the delay counter starts the mcu after the time-out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for lon- ger than t bod given in table 8-1 . figure 8-5. brown-out reset during operation table 8-2. bodlevel fuse coding bodlevel 2..0 fuses min v bot typ v bot max v bot units 111 bod disabled 110 1.8 2.0 2.2 v 101 2.0 2.2 2.4 100 2.2 2.4 2.6 011 2.4 2.6 2.8 010 3.2 3.4 3.6 001 3.3 3.5 3.7 000 4.0 4.3 4.5 table 8-3. brown-out characteristics symbol parameter min typ max units v hyst brown-out detector hysteresis 50 mv t bod min pulse width on brown-out reset ns v cc reset time-out internal reset v bot- v bot+ t tout
53 7766f?avr?11/10 atmega16/32u4 8.0.6 watchdog reset when the watchdog times out, it will generate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to page 55 for details on operation of the watchdog timer. figure 8-6. watchdog reset during operation 8.0.7 usb reset when the usb controller is enabled and confi gured with the usb reset cpu feature enabled and if a valid usb reset signalling is detected on the bus, the cpu core is reset but the usb controller remains enabl ed and attached. this feature may be used to enhance de vice reliability. figure 8-7. usb reset during operation 8.0.8 mcu status register ? mcusr the mcu status register provides information on which reset source caused an mcu reset. ? bit 7..6 - reserved these bits are reserved and should be read as 0. do not set these bits. ck cc cc usb traffic usb traffic dp dm (usb lines) t usbrstmin end of reset bit 76543210 ? ? usbrf jtrf wdrf borf extrf porf mcusr read/write r r r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description
54 7766f?avr?11/10 atmega16/32u4 ? bit 5? usbrf: usb reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog re set occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bi t is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 8.1 internal voltage reference atmega16u4/atmega32u4 features an internal bandgap reference. this reference is used for brown-out detection, and it can be used as an input to the analog comparator or the adc. 8.1.1 voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in table 8-4 . to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by prog ramming the bodlevel [2..0] fuse). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). 3. when the adc is enabled. thus, when the bod is not enabled, after setting the acbg bit or enabling the adc, the user must always allow the reference to start up before the output from the analog comparator or
55 7766f?avr?11/10 atmega16/32u4 adc is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode. note: 1. values are guidelines only. actual values are tbd. 8.2 watchdog timer atmega16u4/atmega32u4 has an enhanced watchdog timer (wdt). the main features are: ? clocked from separat e on-chip oscillator ? 3 operating modes ?interrupt ? system reset ? interrupt and system reset ? selectable time-out period from 16ms to 8s ? possible hardware fuse watchdog al ways on (wdton) for fail-safe mode figure 8-8. watchdog timer the watchdog timer (wdt) is a timer counting cycles of a separa te on-chip 128 khz oscillator. the wdt gives an interrupt or a system reset when the counter reaches a given time-out value. in normal operation mode, it is required that the system uses the wdr - watchdog timer reset - instruction to restart the counter before the ti me-out value is reached. if the system doesn't restart the counter, an interrupt or system reset will be issued. in interrupt mode, the wdt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. in system reset mode, the wdt gives a reset when the timer table 8-4. internal voltage refe rence characteristics (1) symbol parameter condi tion min typ max units v bg bandgap reference voltage tbd tbd 1.1 tbd v t bg bandgap reference start-up time tbd 40 70 s i bg bandgap reference current consumption tbd 10 tbd a 128khz oscillator osc/2k osc/4k osc/8k osc/16k osc/32k osc/64k osc/128k osc/256k osc/512k osc/1024k wdp0 wdp1 wdp2 wdp3 watchdog reset wde wdif wdie mcu reset interrupt
56 7766f?avr?11/10 atmega16/32u4 expires. this is typically used to prevent sys tem hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an inter- rupt and then switch to system reset mode. this mode will for instance allow a safe shutdown by saving critical parameters before a system reset. the watchdog always on (wdton ) fuse, if programmed, will forc e the watchdog timer to sys- tem reset mode. with the fuse programmed the system reset mode bit (wde) and interrupt mode bit (wdie) are locked to 1 and 0 respectively. to further ensure program security, altera- tions to the watchdog set-up must follow timed sequences. the sequence for clearing wde and changing time-out configuration is as follows: 1. in the same operation, write a logic one to the watchdog change enable bit (wdce) and wde. a logic one must be written to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, write the wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. the following code example shows one assembly and one c function for turning off the watch- dog timer. the example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions.
57 7766f?avr?11/10 atmega16/32u4 note: 1. the example code assumes that the pa rt specific header file is included. note: if the watchdog is accidentally enabled, fo r example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to avoid this situation, the application software should always clear the watchdog system reset flag (wdrf) and the wde control bit in the initialization routine, even if the watchdog is not in use. assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 58 7766f?avr?11/10 atmega16/32u4 the following code example shows one assembly and one c function for changing the time-out value of the watchdog timer. note: 1. the example code assumes that the pa rt specific header file is included. note: the watchdog timer should be reset before any change of the wdp bits, since a change in the wdp bits can result in a time-out when switching to a shorter time-out period. 8.2.1 watchdog timer control register - wdtcsr ? bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs in the watchdog timer and the watchdog timer is config- ured for interrupt. wdif is cleared by hardw are when executing the corresponding interrupt assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence in r16, wdtcsr ori r16, (1< 59 7766f?avr?11/10 atmega16/32u4 handling vector. alternatively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchdog time-out interrupt is executed. ? bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i-bit in t he status register is set, the watchdog interrupt is enabled. if wde is cleared in combination with this setting, the watchdog timer is in interrupt mode, and the corresponding interrupt is executed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. the first time-out in the watchdog timer will set wdif. executing t he corresponding interrup t vector will clear wdie and wdif automatically by hardware (the watchd og goes to system reset mode). this is use- ful for keeping the watchdog timer security while using the interrupt. to stay in interrupt and system reset mode, wdie must be set after each interrupt. this should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the watchdog system reset mode. if the interrupt is not executed before the next time-out, a sys- tem reset will be applied. ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changi ng wde and prescaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, ha rdware will clear wdce after four clock cycles. ? bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this m eans that wde is always set when wdrf is set. to clear wde, wdrf must be cleared first. this feature ensures multiple resets during con- ditions causing failure, and a safe start-up after the failure. ? bit 5, 2..0 - wdp3..0: watchdog timer prescaler 3, 2, 1 and 0 the wdp3..0 bits determine the watchdog timer prescaling when the watchdog timer is run- ning. the different prescaling values and thei r corresponding time-out periods are shown in table 8-6 on page 60 . table 8-5. watchdog timer configuration wdton wde wdie mode action on time-out 0 0 0 stopped none 0 0 1 interrupt mode interrupt 0 1 0 system reset mode reset 011 interrupt and system reset mode interrupt, then go to system reset mode 1 x x system reset mode reset
60 7766f?avr?11/10 atmega16/32u4 . table 8-6. watchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 16 ms 0 0 0 1 4k (4096) cycles 32 ms 0 0 1 0 8k (8192) cycles 64 ms 0 0 1 1 16k (16384) cycles 0.125 s 0 1 0 0 32k (32768) cycles 0.25 s 0 1 0 1 64k (65536) cycles 0.5 s 0 1 1 0 128k (131072) cycles 1.0 s 0 1 1 1 256k (262144) cycles 2.0 s 1 0 0 0 512k (524288) cycles 4.0 s 1 0 0 1 1024k (1048576) cycles 8.0 s 1010 reserved 1011 1100 1101 1110 1111
61 7766f?avr?11/10 atmega16/32u4 9. interrupts this section describes the specifics of the interrupt handling as performed in atmega16u4/atmega32u4. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt handling? on page 15 . 9.1 interrupt vectors in atmega16u4/atmega32u4 table 9-1. reset and interrupt vectors vector no. program address (2) source interrup t definition 1 $0000 (1) reset external pin, power-on reset, brown-out reset, watchdog reset, and jtag avr reset 2 $0002 int0 external interrupt request 0 3 $0004 int1 external interrupt request 1 4 $0006 int2 external interrupt request 2 5 $0008 int3 external interrupt request 3 6 $000a reserved reserved 7 $000c reserved reserved 8 $000e int6 external interrupt request 6 9 $0010 reserved reserved 10 $0012 pcint0 pin change interrupt request 0 11 $0014 usb general usb general interrupt request 12 $0016 usb endpoint usb endpoint interrupt request 13 $0018 wdt watchdog time-out interrupt 14 $001a reserved reserved 15 $001c reserved reserved 16 $001e reserved reserved 17 $0020 timer1 capt timer/counter1 capture event 18 $0022 timer1 compa timer/counter1 compare match a 19 $0024 timer1 compb timer /counter1 compare match b 20 $0026 timer1 compc timer /counter1 compare match c 21 $0028 timer1 ovf timer/counter1 overflow 22 $002a timer0 compa timer/counter0 compare match a 23 $002c timer0 compb timer /counter0 compare match b 24 $002e timer0 ovf timer/counter0 overflow 25 $0030 spi (stc) spi serial transfer complete 26 $0032 usart1 rx usart1 rx complete 27 $0034 usart1 udre usart1 data register empty 28 $0036 usart1tx usart1 tx complete 29 $0038 analog comp analog comparator
62 7766f?avr?11/10 atmega16/32u4 notes: 1. when the bootrst fuse is programmed, the device will jump to the boot loader address at reset, see ?memory programming? on page 346 . 2. when the ivsel bit in mcucr is set, interrupt vectors will be moved to the start of the boot flash section. the address of each interrupt vector will then be the address in this table added to the start address of the boot flash section. table 9-2 shows reset and interrupt vectors plac ement for the various combinations of bootrst and ivsel settings. if the program never enables an in terrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application section while the interrupt vectors are in the boot section or vice versa. note: 1. the boot reset address is shown in table 27-8 on page 344 . for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. 9.1.1 moving interrupts between application and boot space the general interrupt control register controls the placement of the interrupt vector table. 30 $003a adc adc conversion complete 31 $003c ee ready eeprom ready 32 $003e timer3 capt timer/counter3 capture event 33 $0040 timer3 compa timer/counter3 compare match a 34 $0042 timer3 compb timer /counter3 compare match b 35 $0044 timer3 compc timer /counter3 compare match c 36 $0046 timer3 ovf timer/counter3 overflow 37 $0048 twi 2-wire serial interface 38 $004a spm ready store program memory ready 39 $004c timer4 compa timer/counter4 compare match a 40 $004e timer4 compb timer /counter4 compare match b 41 $0050 timer4 compd timer /counter4 compare match d 42 $0052 timer4 ovf timer/counter4 overflow 43 $0054 timer4 fpf timer/counter4 fault protection interrupt table 9-2. reset and interrupt vectors placement (1) bootrst ivsel reset address interr upt vectors start address 1 0 0x0000 0x0002 1 1 0x0000 boot reset address + 0x0002 0 0 boot reset address 0x0002 0 1 boot reset address boot reset address + 0x0002 table 9-1. reset and interrupt vectors (continued) vector no. program address (2) source interrup t definition
63 7766f?avr?11/10 atmega16/32u4 9.1.2 mcu control register ? mcucr ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (z ero), the interrupt vectors are pl aced at the star t of the flash memory. when this bit is set (one), the interrupt vectors are moved to the beginning of the boot loader section of the flash. the actual address of the start of the boot flash section is deter- mined by the bootsz fuses. refer to the section ?memory programming? on page 346 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: a. write the interrupt vector change enable (ivce) bit to one. b. within four cycles, write the desired valu e to ivsel while writing a zero to ivce. interrupts will automatically be di sabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabl ed until after the instru ction following the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. note: if interrupt vectors are placed in the boot loader section and boot lock bit blb02 is programmed, interrupts are disabled while executing from the a pplication section. if interrupt vectors are placed in the application section and boot lock bit blb 12 is programed, interrupts are disabled while executing from the boot loader section. refer to the section ?memory programmi ng? on page 346 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of the ivsel bit. ivce is cleared by hardware four cyc les after it is written or when ivsel is written. sett ing the ivce bit will disable interrupts, as explained in the ivsel description above. see code example below. bit 76543210 jtd ? ? pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
64 7766f?avr?11/10 atmega16/32u4 assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 65 7766f?avr?11/10 atmega16/32u4 10. i/o-ports 10.1 introduction all avr ports have true read-modi fy-write functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when chang- ing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin driver is stro ng enough to drive led displays directly. all port pins have indi- vidually selectable pull-up resistors with a suppl y-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 10-1 . refer to ?electrical char- acteristics? on page 378 for a complete list of parameters. figure 10-1. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? repre- sents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a progr am, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o regis- ters and bit locations are listed in ?register description for i/o-ports? on page 82 . three i/o memory address locations are allocated for each port, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bit in the pinx register, will result in a toggle in the correspond- ing bit in the data register. in addition, the pu ll-up disable ? pud bit in mcucr disables the pull-up function for all pins in all ports when set. using the i/o port as general digital i/o is described in ?ports as general digital i/o? on page 66 . most port pins are multiplexed with alternate functions for the peripheral features on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 70 . refer to the individual module sectio ns for a full description of the alter- nate functions.
66 7766f?avr?11/10 atmega16/32u4 note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. 10.2 ports as gener al digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 10-2 shows a func- tional description of one i/o-port pin, here generically called pxn. figure 10-2. general digital i/o (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 10.2.1 configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description for i/o-ports? on page 82 , the ddxn bits are accessed at the ddrx i/o address, the portxn bits at the portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direct ion of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is configured as an input pin. if portxn is written logic one when the pin is c onfigured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data bus sleep sleep: sleep control pxn i/o wpx 0 1 wrx wpx: write pinx register
67 7766f?avr?11/10 atmega16/32u4 if portxn is written logic one when the pin is conf igured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). 10.2.2 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi instruction can be used to toggle one single bit in a port. 10.2.3 switching between input and output when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled {ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) occurs. normally, the pull-up enabled state is fully acceptable, as a high-impedance envi ronment will not notice the difference between a strong high driver and a pull-up. if this is not the case, the pud bit in th e mcucr register can be set to disable all pull- ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 10-1 summarizes the control signals for the pin value. 10.2.4 reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 10-2 , the pinxn register bit and the preceding latch con- stitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 10-3 shows a timing dia- gram of the synchronization when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. table 10-1. port pin configurations ddxn portxn pud (in mcucr) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source)
68 7766f?avr?11/10 atmega16/32u4 figure 10-3. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system cl ock. the latch is closed when the clock is low, and goes transpa rent when the clock is high, as indicated by the shaded region of the ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the succeeding positive clock edge. as indi- cated by the two arrows tpd max and tpd min, a single signal tran sition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 10-4 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. figure 10-4. synchronization when reading a software assigned pin value the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
69 7766f?avr?11/10 atmega16/32u4 note: 1. for the assembly program, two temporary registers are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 10.2.5 digital input enable and sleep modes as shown in figure 10-2 , the digital input signal can be clamped to ground at the input of the schmidt-trigger. the signal denoted sleep in the fi gure, is set by the mcu sleep controller in power-down mode, power-save mode, and standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as ex ternal interrupt pins. if the external interrupt request is not e nabled, sleep is active also for these pins. sl eep is also overri dden by various other alternate functions as described in ?alternate port functions? on page 70 . if a logic high level (?one?) is present on an asynchronous external interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sleep mode, as the clamping in these sleep mode produces the requested logic change. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 70 7766f?avr?11/10 atmega16/32u4 10.2.6 unconnected pins if some pins are unused, it is recommended to ens ure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull-up will be disabled during reset. if low po wer consumption during reset is important, it is recommended to use an external pull-up or pull-down. connecting unused pins directly to v cc or gnd is not recommended, since this ma y cause excessive curr ents if the pin is accidentally configured as an output. 10.3 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 10-5 shows how the port pin control signals from the simplified figure 10-2 can be overridden by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr microcontroller family. figure 10-5. alternate port functions (1) clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data bus 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn ptoexn: pxn, port toggle override enable wpx: write pinx wpx
71 7766f?avr?11/10 atmega16/32u4 note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. table 10-2 summarizes the function of the overriding signals. the pin and port indexes from fig- ure 10-5 are not shown in the succeeding tables. the overriding signals are generated internally in the modules having the alternate function. the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. refer to the alternate function description for further details. table 10-2. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the mcu state (normal mode, sleep mode). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi-directionally.
72 7766f?avr?11/10 atmega16/32u4 10.3.1 mcu control register ? mcucr ? bit 4 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?con- figuring the pin? on page 66 for more details about this feature. 10.3.2 alternate functions of port b the port b pins with alternate functions are shown in table 10-3 . the alternate pin configuration is as follows: ? oc0a/oc1c/pcint7/rts , bit 7 oc0a, output compare match a output: the pb7 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc0a pin is also th e output pin for the pwm mode timer function. oc1c, output compare match c output: the pb7 pi n can serve as an external output for the timer/counter1 output compare c. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc1c pin is also the output pin for the pwm mode timer function. pcint7, pin change interrupt source 7: the pb7 pin can serve as an external interrupt source. rts : rts flow control signal used by enhanced uart. bit 7 6 5 4 3 2 1 0 jtd ? ?pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 10-3. port b pins alternate functions port pin alternate functions pb7 oc0a/oc1c/pcint7/rts (output compare and pwm output a for timer/counter0, output compare and pwm output c for timer/counter1 or pin change interrupt 7 or uart flow control rts signal) pb6 oc1b/pcint6/oc.4b/adc1 3 (output compare and pwm output b for timer/counter1 or pin change interrupt 6 or timer 4 output compare b / pwm output or analog to digital converter channel 13) pb5 oc1a/pcint5/oc.4b /adc12 (output compare and pwm output a for timer/counter1 or pin change interrupt 5 or timer 4 complementary output compare b / pwm output or analog to digital converter channel 12) pb4 pcint4/adc11 (pin change interrupt 4 or analog to digital converter channel 11) pb3 pdo/miso/pcint3 (programmi ng data output or spi bus master input/slave output or pin change interrupt 3) pb2 pdi/mosi/pcint2 (programming data input or spi bus master output/slave input or pin change interrupt 2) pb1 sck/pcint1 (spi bus serial clo ck or pin change interrupt 1) pb0 ss /pcint0 (spi slave select input or pin change interrupt 0)
73 7766f?avr?11/10 atmega16/32u4 ? oc1b/pcint6/oc.4b/adc12, bit 6 oc1b, output compare match b output: the pb6 pin can serve as an external output for the timer/counter1 output compare b. the pin has to be configured as an output (ddb6 set ?one?) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. pcint6, pin change interrupt source 6: the pb7 pin can serve as an external interrupt source. oc.4b: timer 4 output compare b. this pin can be used to generate a high-speed pwm signal from timer 4 module. the pin has to be configured as an output (ddb6 set ?one?) to serve this function. adc13: analog to digital converter, channel 13. ? oc1a/pcint5/oc.4b /adc12, bit 5 oc1a, output compare match a output: the pb5 pin can serve as an external output for the timer/counter1 output compare a. the pin has to be configured as an output (ddb5 set (one)) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. pcint5, pin change interrupt source 5: the pb7 pin can serve as an external interrupt source. oc.4b : timer 4 output compare b. this pin can be used to generate a high-speed pwm signal from timer 4 module, complementary to oc.4b (pb5) signal. the pin has to be configured as an output (ddb5 set (one)) to serve this function. adc12: analog to digital converter, channel 12. ? pcint4/adc11, bit 4 pcint4, pin change interrupt source 4: the pb7 pin can serve as an external interrupt source. adc11, analog to digital converter channel 11. ? pdo/miso/pcint3 ? port b, bit 3 pdo, spi serial programming data output. duri ng serial program downloading, this pin is used as data output line for the atmega16u4/atmega32u4. miso: master data input, slave data output pin for spi channel. when the spi is enabled as a master, this pin is configured as an input r egardless of the setting of ddb3. when the spi is enabled as a slave, the data direction of this pi n is controlled by ddb3. when the pin is forced to be an input, the pull- up can still be controlled by the portb3 bit. pcint3, pin change interrupt source 3: the pb7 pin can serve as an external interrupt source. ? pdi/mosi/pcint2 ? port b, bit 2 pdi, spi serial programming data input. during serial program downloading, this pin is used as data input line for the atmega16u4/atmega32u4. mosi: spi master data output, slave data input for spi channel. when the spi is enabled as a slave, this pin is configured as an input regar dless of the setting of ddb2. when the spi is enabled as a master, the data direction of this pi n is controlled by ddb2. when the pin is forced to be an input, the pull-up can st ill be controlled by the portb2 bit. pcint2, pin change interrupt source 2: the pb7 pin can serve as an external interrupt source.
74 7766f?avr?11/10 atmega16/32u4 ? sck/pcint1 ? port b, bit 1 sck: master clock output, slave clock input pin for spi channel. when the spi is enabled as a slave, this pin is configured as an input regar dless of the setting of ddb1. when the spi0 is enabled as a master, the data direction of this pi n is controlled by ddb1. when the pin is forced to be an input, the pull-up can st ill be controlled by the portb1 bit. pcint1, pin change interrupt source 1: the pb7 pin can serve as an external interrupt source. ?ss /pcint0 ? port b, bit 0 ss : slave port select input. when the spi is enab led as a slave, this pin is configured as an input regardless of the setting of ddb0. as a slav e, the spi is activated when this pin is driven low. when the spi is enabled as a master, the data di rection of this pin is controlled by ddb0. when the pin is forced to be an input, the pull-up can still be controlled by the portb0 bit. table 10-4 and table 10-5 relate the alternate functions of port b to the overriding signals shown in figure 10-5 on page 70 . spi mstr input and spi sl ave output constitute the miso signal, while mosi is divided in to spi mstr output and spi slave input. pcint0, pin change interrupt source 0: the pb7 pin can serve as an external interrupt source.. table 10-4. overriding signals for alternate functions in pb7.pb4 signal name pb7/pcint7/oc0a/ oc1c/rts pb6/pcint6/oc1 b/oc.4b/adc13 pb5/pcint5/oc1 a/oc.4b /adc12 pb4/pcint4/a dc11 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc0/oc1c enable oc1b enable oc1a enable 0 pvov oc0/oc1c oc1b oc1a 0 dieoe pcint7 ? pcie0 pcint6 ? pcie0 pcint5 ? pcie0 pcint4 ? pcie0 dieov 1 1 1 1 di pcint7 input pcint6 input pcint5 input pcint4 input aio ? ? ? ?
75 7766f?avr?11/10 atmega16/32u4 10.3.3 alternate functions of port c the port c alternate function is as follows: ? icp3/clko/oc.4a ? port c, bit 7 icp3: if timer 3 is correctly configured, this pin can serve as input capture feature. clko: when the corresponding fuse is enabled, this pin outputs the internal microcontroller working frequency. if the cloc k prescaler is used, this will af fect this out put frequency. oc.4a: timer 4 output compare a. this pin can be used to generate a high-speed pwm signal from timer 4 module. the pin has to be configured as an output (ddc7 set ?one?) to serve this function. table 10-5. overriding signals for alternate functions in pb3.pb0 signal name pb3/pd0/pcint3/ miso pb2/pdi/pcint2/ mosi pb1/pcint1/ sck pb0/pcint0/ ss puoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr puov portb3 ? pud portb2 ? pud portb1 ? pud portb0 ? pud ddoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr ddov 0 0 0 0 pvoe spe ? mstr spe ? mstr spe ? mstr 0 pvov spi slave output spi mstr output sck output 0 dieoe pcint3 ? pcie0 pcint2 ? pcie0 pcint1 ? pcie0 pcint0 ? pcie0 dieov 1 1 1 1 di spi mstr input pcint3 input spi slave input pcint2 input sck input pcint1 input spi ss pcint0 input aio ? ? ? ? table 10-6. port c pins alternate functions port pin alternate function pc7 icp3/clko/oc4a(input capture timer 3 or clk0 (divided system clock) or output compare and direct pwm output a for timer 4) pc6 oc.3a/oc4a (output compare and pwm output a for timer/counter3 or output compare and complementary pwm output a for timer 4) pc5 not present on pin-out. pc4 pc3 pc2 pc1 pc0
76 7766f?avr?11/10 atmega16/32u4 ? oc.3a/oc.4a ? port c, bit 6 oc.3a: timer 3 output compare a. this pin c an be used to generate a pwm signal from timer 3 module. oc.4a : timer 4 output compare a . this pin can be used to generate a high-speed pwm signal from timer 4 module, complementary to oc.4a (pc7) signal. the pin has to be configured as an output (ddc6 set ?one?) to serve this function. table 10-7 relate the alternate functions of port c to the overriding signals shown in figure 10-5 on page 70 . table 10-7. overriding signals for alte rnate functions in pc7.pc6 signal name pc7/icp3/clko/oc.4 a pc6/oc.3a/oc.4a puoe sre ? (xmm<1) sre ? (xmm<2)|oc3a enable puov 0 0 ddoe sre ? (xmm<1) sre ? (xmm<2) ddov 1 1 pvoe sre ? (xmm<1) sre ? (xmm<2) pvov a15 if (sre.xmm<2) then a14 else oc3a dieoe 0 0 dieov 0 0 di icp3 input ? aio ? ?
77 7766f?avr?11/10 atmega16/32u4 10.3.4 alternate functions of port d the port d pins with alternate functions are shown in table 10-8 . the alternate pin configuration is as follows: ? t0/oc.4d/adc10 ? port d, bit 7 t0, timer/counter0 counter source. oc.4d: timer 4 output compare d. this pin can be used to generate a high-speed pwm signal from timer 4 module. the pin has to be configured as an output (ddd7 set ?one?) to serve this function. adc10: analog to digital converter, channel 10. ? t1/oc.4d /adc9 ? port d, bit 6 t1, timer/counter1 counter source. oc.4d : timer 4 output compare d. this pin can be used to generate a high-speed pwm signal from timer 4 module, complementary to oc.4d (pd7) signal. the pin has to be configured as an output (ddd6 set ?one?) to serve this function. adc9: analog to digital converter, channel 9 . ? xck1/cts ? port d, bit 5 xck1, usart1 external clock. th e data direction register (ddd5) controls whether the clock is output (ddd5 set) or input (ddd5 cleared). the xck1 pin is active only when the usart1 operates in synchronous mode. cts : clear-to-send flow control signal used by enhanced uart module. ? icp1/adc8 ? port d, bit 4 icp1 ? input capture pin 1: the pd4 pin can ac t as an input capture pin for timer/counter1. adc8: analog to digital converter, channel 8 . table 10-8. port d pins alternate functions port pin alternate function pd7 t0/oc.4d/adc10 (timer/counter0 clock input or timer 4 output compare d / pwm output or analog to digital converter channel 10) pd6 t1/oc.4d /adc9 (timer/counter1 clock input or timer 4 output complementary compare d / pwm output or analog to digital converter channel 9) pd5 xck1/cts (usart1 external clock input/output or uart flow control cts signal) pd4 icp1/adc8 (timer/counter1 input capt ure trigger or analog to digital converter channel 8) pd3 int3 /txd1 (external interrupt3 input or usart1 transmit pin) pd2 int2 /rxd1 (external interrupt2 input or usart1 receive pin) pd1 int1 /sda (external interrupt1 input or twi serial data) pd0 int0 /scl/oc0b (external interrupt0 input or twi serial clock or output compare for timer/counter0)
78 7766f?avr?11/10 atmega16/32u4 ?int3 /txd1 ? port d, bit 3 int3, external interrupt source 3: the pd3 pin c an serve as an external interrupt source to the mcu. txd1, transmit data (data output pin for t he usart1). when the usart1 transmitter is enabled, this pin is configured as an output regardless of the value of ddd3. ?int2 /rxd1 ? port d, bit 2 int2, external interrupt source 2. the pd2 pin can serve as an external interrupt source to the mcu. rxd1, receive data (data input pin for the u sart1). when the usart1 receiver is enabled this pin is configured as an input regardless of the value of ddd2. when the usart forces this pin to be an input, the pull-up can still be controlled by the portd2 bit. ?int1 /sda ? port d, bit 1 int1, external interrupt source 1. the pd1 pin c an serve as an external interrupt source to the mcu. sda, 2-wire serial interface data: when the twen bit in twcr is set (one) to enable the 2-wire serial interface, pin pd1 is disconnected from t he port and becomes the serial data i/o pin for the 2-wire serial interface. in this mode, ther e is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew- rate limitation. ?int0 /scl/oc0b ? port d, bit 0 int0, external interrupt source 0. the pd0 pin c an serve as an external interrupt source to the mcu. scl, 2-wire serial interface clock: when the tw en bit in twcr is set (one) to enable the 2- wire serial interface, pin pd0 is disconnect ed from the port and becomes the serial clock i/o pin for the 2-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. oc.0b: timer 0 output compare b. this pin can be used to generate a pwm signal from the timer 0 module. table 10-9 and table 10-10 relates the alternate functions of port d to the overriding signals shown in figure 10-5 on page 70 .
79 7766f?avr?11/10 atmega16/32u4 note: 1. when enabled, the 2-wire serial interface enables slew-rate controls on the output pins pd0 and pd1. this is not shown in this table. in addition, spike filters are connected between the aio outputs shown in the port figure and the digital logic of the twi module. table 10-9. overriding signals for alternate functions pd7..pd4 signal name pd7/t0/ oc4d/adc10 pd6/t1/ oc4d /adc9 pd5/xck1/cts pd4/icp1/ adc8 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 xck1 output enable 0 ddov 0 0 1 0 pvoe 0 0 xck1 output enable 0 pvov 0 0 xck1 output 0 dieoe 0 0 0 0 dieov 0 0 0 0 di t0 input t1 input xck1 input icp1 input aio ? ? ? ? table 10-10. overriding signals for alte rnate functions in pd3.pd0 (1) signal name pd3/int3/txd1 p d2/int2/rxd1 pd1/int1/sda pd0/int0/scl/ oc0b puoe txen1 rxen1 twen twen puov 0 portd2 ? pud portd1 ? pud portd0 ? pud ddoe txen1 rxen1 twen twen ddov 1 0 sda_out scl_out pvoe txen1 0 twen enable twen | oc0b enable pvov txd1 0 0 oc0b dieoe int3 enable int2 enable int1 enable int0 enable dieov 1 1 1 1 di int3 input int2 input/rxd1 int1 input int0 input aio ? ? sda input scl input
80 7766f?avr?11/10 atmega16/32u4 10.3.5 alternate functions of port e the port e pins with alternate functions are shown in table 10-11 . ? int6/ain0 ? port e, bit 6 int6, external interrupt source 6: the pe6 pin can serve as an external interrupt source. ain0 ? analog comparator negative input. this pi n is directly connected to the negative input of the analog comparator. ?hwb ? port e, bit 2 hwb allows to execute the bootloader section after reset when tied to ground during external reset pulse. the hwb mode of this pin is active only when the hwbe fuse is enable. during nor- mal operation (excluded reset), this pin acts as a general purpose i/o. 10.3.6 alternate functions of port f the port f has an alternate function as analog input for the adc as shown in table 10-13 . if some port f pins are configured as outputs, it is essential that these do not switch when a con- version is in progress. this might corrupt the re sult of the conversion. if the jtag interface is table 10-11. port e pins alternate functions port pin alternate function pe7 not present on pin-out. pe6 int6/ain0 (external interrupt 6 input or analog comparator positive input) pe5 not present on pin-out. pe4 pe3 pe2 hwb (hardware bootloader activation) pe1 not present on pin-out. pe0 table 10-12. overriding signals for alternate functions pe6, pe2 signal name pe6/int6/ain0 pe2/hwb puoe 0 0 puov 0 0 ddoe 0 0 ddov 0 1 pvoe 0 0 pvov 0 0 dieoe int6 enable 0 dieov 1 0 di int6 input hwb aio ain0 input -
81 7766f?avr?11/10 atmega16/32u4 enabled, the pull-up resistors on pins pf7(tdi), pf5(tms), an d pf4(tck) will be activated even if a reset occurs. ? tdi, adc7 ? port f, bit 7 adc7, analog to digital converter, channel 7 . tdi, jtag test data in: serial input data to be shifted in to the instruction register or data reg- ister (scan chains). when the jtag interface is enabled, this pin can not be used as an i/o pin. ? tdo, adc6 ? port f, bit 6 adc6, analog to digital converter, channel 6 . tdo, jtag test data out: serial output data from instruction register or data register. when the jtag interface is enabled, this pin can not be used as an i/o pin. the tdo pin is tri-stated unless tap states that shift out data are entered. ? tms, adc5 ? port f, bit 5 adc5, analog to digital converter, channel 5 . tms, jtag test mode select: this pin is used fo r navigating through the tap-controller state machine. when the jtag interface is enabled, this pin can not be used as an i/o pin. ? tck, adc4 ? port f, bit 4 adc4, analog to digital converter, channel 4 . tck, jtag test clock: jtag operation is synch ronous to tck. when the jtag interface is enabled, this pin can not be used as an i/o pin. ? adc3 ? adc0 ? port f, bit 1..0 analog to digital converter, channel 1.0 table 10-13. port f pins alternate functions port pin alternate function pf7 adc7/tdi (adc input channel 7 or jtag test data input) pf6 adc6/tdo (adc input channel 6 or jtag test data output) pf5 adc5/tms (adc input channel 5 or jtag test mode select) pf4 adc4/tck (adc input channel 4 or jtag test clock) pf3 not present on pin-out. pf2 pf1 adc1 (adc input channel 1) pf0 adc0 (adc input channel 0)
82 7766f?avr?11/10 atmega16/32u4 . 10.4 register descrip tion for i/o-ports 10.4.1 port b data register ? portb table 10-14. overriding signals for alternate functions in pf7..pf4 signal name pf7/adc7/tdi pf6/adc6/td o pf5/adc5/tms pf4/adc4/tck puoe jtagen jtagen jtagen jtagen puov 1 0 1 1 d d o e j tag e n j tag e n j tag e n j tag e n ddov 0 shift_ir + shift_dr 00 pvoe 0 jtagen 0 0 pvov 0 tdo 0 0 d i e o e j tag e n j tag e n j tag e n j tag e n dieov 0 0 0 0 di ? ? ? ? aio tdi/adc7 input adc6 input tms/adc5 input tck/adc4 input table 10-15. overriding signals for alternate functions in pf1..pf0 signal name pf1/adc1 pf0/adc0 puoe 0 0 puov 0 0 ddoe 0 0 ddov 0 0 pvoe 0 0 pvov 0 0 dieoe 0 0 dieov 0 0 di ? ? aio adc1 input adc0 input bit 76543210 portb 7 portb 6 portb 5 portb 4 portb 3 portb 2 portb 1 portb 0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
83 7766f?avr?11/10 atmega16/32u4 10.4.2 port b data direction register ? ddrb 10.4.3 port b input pins address ? pinb 10.4.4 port c data register ? portc 10.4.5 port c data direction register ? ddrc 10.4.6 port c input pins address ? pinc 10.4.7 port d data register ? portd 10.4.8 port d data direction register ? ddrd 10.4.9 port d input pins address ? pind bit 76543210 ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinb7 pinb6 pinb5 pinb4 pi nb3 pinb2 pinb1 pinb0 pinb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portc 7 portc 6 ------portc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddc7ddc6------ ddrc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinc7pinc6------pinc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portd 7 portd 6 portd 5 portd 4 portd 3 portd 2 portd 1 portd 0 portd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pind7 pind6 pind5 pind4 pi nd3 pind2 pind1 pind0 pind read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a
84 7766f?avr?11/10 atmega16/32u4 10.4.10 port e data register ? porte 10.4.11 port e data direction register ? ddre 10.4.12 port e input pins address ? pine 10.4.13 port f data register ? portf 10.4.14 port f data direction register ? ddrf 10.4.15 port f input pins address ? pinf bit 76543210 -porte 6 ---porte 2 --porte read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 - dde6 - - - dde2 - - ddre read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 -pine6---pine2--pine read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portf 7 portf 6 portf 5 portf 4 --portf 1 portf 0 portf read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddf7 ddf6 ddf5 ddf4 - - ddf1 ddf0 ddrf read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinf7 pinf6 pinf5 pinf4 - - pinf1 pinf0 pinf read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a
85 7766f?avr?11/10 atmega16/32u4 11. external interrupts the external interrupts are triggered by the int6, int3:0 pin or any of the pcint7..0 pins. observe that, if enabled, the interrupts will trigger even if the int[6;3:0] or pcint7..0 pins are configured as outputs. this feature provides a way of generating a software interrupt. the pin change interrupt pci0 will trigger if an y enabled pcint7:0 pin toggles. pcmsk0 regis- ter control which pins contribute to the pin change interrupts. pin change interrupts on pcint7 ..0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the external interrupts can be triggered by a falli ng or rising edge or a low level. this is set up as indicated in the specification for the external interrupt control registers ? eicra (int3:0) and eicrb (int6). when the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. note that recognition of falling or rising edge interrupts on int6 requires the presence of an i/o clock, described in ?system clock and clock options? on page 27 . low level interrupts and the edge interrupt on int3:0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down, the required level must be held long enough for the mcu to complete the wake-up to trigger the level interrupt. if the level disappears before the end of the start-up ti me, the mcu will still wake up, but no inter- rupt will be generated. the start- up time is defined by the su t and cksel fuses as described in ?system clock and clock options? on page 27 . 11.0.1 external interrupt control register a ? eicra the external interrupt control register a contains control bits for interrupt sense control. ? bits 7..0 ? isc31, isc30 ? isc00, isc00: external interrupt 3 - 0 sense control bits the external interrupts 3 - 0 are activated by the external pins int3:0 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 11-1 . edges on int3..int0 are registered asynchro- nously. pulses on int3:0 pins wider than the minimum pulse width given in table 11-2 will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an inter- rupt request as long as the pin is held low. when changing the iscn bit, an interrupt can occur. therefore, it is recommended to first disable intn by clearing its interrupt enable bit in the eimsk register. then, the iscn bit can be changed. finally, the intn interrupt flag should be cleared by writing a logical one to its interrupt flag bit (intfn) in the eifr register before the interrupt is re-enabled. bit 76543210 isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 eicra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
86 7766f?avr?11/10 atmega16/32u4 note: 1. n = 3, 2, 1or 0. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. 11.0.2 external interrupt control register b ? eicrb ? bit 7..6 ? res: reserved bits these bits are reserved bits in the atmega16u4/atmega32u4 and always read as zero. ? bits 5, 4 ? isc61, isc60: external interrupt 6 sense control bits the external interrupt 6 is activated by the exte rnal pin int6 if the sreg i-flag and the corre- sponding interrupt mask in the eimsk is set. the level and edges on the external pin that activate the interrupt are defined in table 11-3 . the value on the int6 pin are sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. observe that cpu clock frequency can be lower than the xtal frequency if the xtal divider is enabled. if low level interrupt is selected, the lo w level must be held unt il the completion of the currently executing instru ction to generate an interrupt. if e nabled, a level trig gered inte rrupt will generate an interrupt request as long as the pin is held low. note: 1. when changing the isc61/isc60 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. table 11-1. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of intn generates an interrupt request. 0 1 any edge of intn generates asynchronously an interrupt request. 1 0 the falling edge of intn generates asynchronously an interrupt request. 1 1 the rising edge of intn generates asynchronously an interrupt request. table 11-2. asynchronous external interrupt characteristics symbol parameter condi tion min typ max units t int minimum pulse width for asynchronous external interrupt 50 ns bit 76543210 - - isc61 isc60 - - - - eicrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 11-3. interrupt sense control (1) isc61 isc60 description 0 0 the low level of int6 generates an interrupt request. 0 1 any logical change on int6 generates an interrupt request 10 the falling edge between two samples of int6 generates an interrupt request. 11 the rising edge between two samples of int6 generates an interrupt request.
87 7766f?avr?11/10 atmega16/32u4 ? bit 3..0 ? res: reserved bits these bits are reserved bits in the atmega16u4/atmega32u4 and always read as zero. 11.0.3 external interrupt mask register ? eimsk ? bits 7..0 ? int6, int3 ? int0: external interrupt request 6, 3 - 0 enable when an int[6;3:0] bit is written to one and the i-bit in the status register (sreg) is set (one), the corresponding external pin interrupt is enabl ed. the interrupt sense control bits in the exter- nal interrupt control registers ? eicra and eicrb ? defines whether the external interrupt is activated on rising or falling ed ge or level sensed. activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. this provides a way of generating a software interrupt. 11.0.4 external interrupt flag register ? eifr ? bits 7..0 ? intf6, intf3 - intf0: external interrupt flags 6, 3 - 0 when an edge or logic change on the int[6;3:0] pin triggers an interrupt request, intf7:0 becomes set (one). if the i-bit in sreg and the corresponding interrupt enable bit, int[6;3:0] in eimsk, are set (one), the mcu will jump to the interrupt vector . the flag is cleared when the interrupt routine is executed. alternatively, the fl ag can be cleared by writing a logical one to it. these flags are always cleared when int[6;3:0] are configured as level interrupt. note that when entering sleep mode with the int3:0 interrupts disabled, the input buffers on these pins will be disabled. this may cause a logic change in internal signals whic h will set the intf3:0 flags. see ?digital input enable and sleep modes? on page 69 for more information. 11.0.5 pin change interrupt control register - pcicr ? bit 0 ? pcie0: pin change interrupt enable 0 when the pcie0 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 0 is enabled. any change on any enabled pcint7..0 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci0 interrupt vector. pcint7..0 pins are enabled individually by the pcmsk0 register. 11.0.6 pin change interrupt flag register ? pcifr bit 76543210 - int6 - - int3 int2 int1 iint0 eimsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 - intf6 - - intf3 intf2 intf1 iintf0 eifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? ? ? ? ?pcie0pcicr read/writerrrrrrrr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ? ? ? ?pcif0pcifr read/writerrrrrrrr/w initial value 0 0 0 0 0 0 0 0
88 7766f?avr?11/10 atmega16/32u4 ? bit 0 ? pcif0: pin change interrupt flag 0 when a logic change on any pcint7..0 pin triggers an interrupt request, pcif0 becomes set (one). if the i-bit in sreg and the pcie0 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alter- natively, the flag can be cleared by writing a logical one to it. 11.0.7 pin change mask register 0 ? pcmsk0 ? bit 7..0 ? pcint7..0: pin change enable mask 7..0 each pcint7..0 bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
89 7766f?avr?11/10 atmega16/32u4 12. timer/counter0, timer/counter1 , and timer/counter3 prescalers timer/counter0, 1, and 3 share the same prescaler module, but the timer/counters can have different prescaler settings. the description below applies to all timer/counters. tn is used as a general name, n = 0, 1 or 3. 12.1 internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn2:0 = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. 12.2 prescaler reset the prescaler is free running, i.e., operates independently of the clock select logic of the timer/counter, and it is shared by the timer/counter tn. since the prescaler is not affected by the timer/counter?s clock select, the state of the prescaler will ha ve implications for situations where a prescaled clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing the timer/counter to program execu- tion. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a prescaler reset will affect the prescaler period for all timer/coun ters it is connected to. 12.3 external clock source an external clock source applied to the tn pin can be used as timer/counter clock (clk tn ). the tn pin is sampled once every system clock cycle by the pin synchronization logic. the synchro- nized (sampled) signal is then passed through the edge detector. figure 12-1 shows a functional equivalent block diagram of the tn synchronizati on and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk tn pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 12-1. tn/t0 pin sampling the synchronization and e dge detector logic introduces a de lay of 2.5 to 3.5 system clock cycles from an edge has been applied to the tn pin to the counter is updated. enabling and disabling of the clock input must be done when tn has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
90 7766f?avr?11/10 atmega16/32u4 each half period of the external clock applie d must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the sys- tem clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling fre- quency (nyquist sampling theorem). however, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 12-2. prescaler for synchronous timer/counters note: t3 input is not available on the atmega16u4/atmega32u4 products. ?tn? only refers to either t0 or t1 inputs. 12.4 general timer/counter control register ? gtccr ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activates the timer/counter synchronization mode. in this mode, the value that is written to the psrasy and psrsyn c bits is kept, hence keeping the correspond- ing prescaler reset signals asserted. this ensures that the corresponding timer/counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. wh en the tsm bit is written to zero, the psrasy and psrsync bits are cleared by hardware, and the timer/counte rs start counting simultaneously. ? bit 0 ? psrsync: prescaler reset for synchronous timer/counters when this bit is one, timer/ counter0 and timer/counter1 and timer/counter3 prescaler will be reset. this bit is normally clea red immediately by hardware, except if the tsm bit is set. note that timer/counter0, timer/counter1 and timer/counter3 share the same prescaler and a reset of this prescaler will affect all timers. psr10 clear tn tn clk i/o synchronization synchronization timer/countern clock source clk tn timer/countern clock source clk tn csn0 csn1 csn2 csn0 csn1 csn2 bit7654 3210 tsm ? ? ? ? ? psrasy psrsync gtccr read/write r/w r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
91 7766f?avr?11/10 atmega16/32u4 13. 8-bit timer/counter0 with pwm timer/counter0 is a general purpose 8-bit time r/counter module, with two independent output compare units, and with pwm support. it allows accurate program execution timing (event man- agement) and wave generation. the main features are: ? two independent output compare units ? double buffered outp ut compare registers ? clear timer on compare match (auto reload) ? glitch free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? three independent interrupt sources (tov0, ocf0a, and ocf0b) 13.1 overview a simplified block diagram of the 8-bit timer/counter is shown in figure 13-1 . for the actual placement of i/o pins, refer to ?pinout atmega16u4/atmega32u4? on page 3 . cpu accessible i/o registers, including i/o bits and i/o pins, ar e shown in bold. the device-specific i/o register and bit locations are listed in the ?8-bit timer/counter register description? on page 102 . figure 13-1. 8-bit timer/counter block diagram 13.1.1 registers the timer/counter (tcnt0) and output compare registers (ocr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req . in the figure) signals are all visible in the timer interrupt flag register (t ifr0). all interrupts are individually masked with the timer inter- rupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). clock select timer/counter data bus ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb tn edge detector ( from prescaler ) clk tn
92 7766f?avr?11/10 atmega16/32u4 the double buffered output compare registers (ocr0a and ocr0b) are compared with the timer/counter value at all times. the result of the compare can be used by the waveform gen- erator to generate a pwm or variable frequency output on the output compare pins (oc0a and oc0b). see ?output compare unit? on page 93. for details. the comp are match event will also set the compare flag (ocf0a or ocf0b) which can be used to generate an output compare interrupt request. 13.1.2 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output com- pare unit, in this case compare unit a or compare unit b. howe ver, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 counter value and so on. the definitions in the table below are also used extensively throughout the document. 13.2 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the timer/counter control register (tccr0b). for details on clock sources and pres- caler, see ?timer/counter0, timer/counter1, and timer/counter3 prescalers? on page 89 . 13.3 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 13-2 shows a block diagram of the counter and its surroundings. figure 13-2. counter unit block diagram signal description (internal signals): count increment or decrement tcnt0 by 1. direction select between increment and decrement. table 13-1. bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is dependent on the mode of operation. data b u s tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear
93 7766f?avr?11/10 atmega16/32u4 clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has re ached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). w hen no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0a) and the wgm02 bit located in the timer/counter control register b (tccr0b). there are clos e connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc0a and oc0b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 96 . the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the wgm02:0 bits. tov0 can be used for generating a cpu interrupt. 13.4 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare registers (ocr0a and ocr0b). whenever tcnt0 equals ocr0a or ocr0b, the comparator signals a match. a match will set the output compare flag (ocf0a or ocf0 b) at the next timer clock cycle. if the corresponding interrupt is enabled, the output compare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is exe- cuted. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the matc h signal to generate an output according to operating mode set by the wgm02:0 bits and compare output mode (com0x1:0) bits. the max and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 96 ). figure 13-3 shows a block diagram of the output compare unit.
94 7766f?avr?11/10 atmega16/32u4 figure 13-3. output compare unit, block diagram the ocr0x registers are double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the dou- ble buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0x register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffering is dis- abled the cpu will access the ocr0x directly. 13.4.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force outp ut compare (foc0x) bit. forcin g compare match will not set the ocf0x flag or reload/clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the com0x1:0 bits settings de fine whether the oc0x pin is set, cleared or toggled). 13.4.2 compare match bloc king by tcnt0 write all cpu write operations to the tcnt0 register will block any compare ma tch that occur in the next timer clock cycle, even when the timer is stopped. this feature allows ocr0x to be initial- ized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. 13.4.3 using the output compare unit since writing tcnt0 in any mo de of operation will block all compare matches for one timer clock cycle, there are risks involved when ch anging tcnt0 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform ocfn x (int.req.) = (8-bit comparator ) ocrnx ocnx data b u s tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
95 7766f?avr?11/10 atmega16/32u4 generation. similarly, do not write the tcnt0 value equal to bottom when the counter is down-counting. the setup of the oc0x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output com- pare (foc0x) strobe bits in normal mode. the oc0x registers keep their values even when changing between waveform generation modes. be aware that the com0x1:0 bits are not doubl e buffered together with the compare value. changing the com0x1:0 bits will take effect immediately. 13.5 compare match output unit the compare output mode (com0x1:0) bits have two functions. the waveform generator uses the com0x1:0 bits for defining the output compare (oc0x) state at the next compare match. also, the com0x1:0 bits control the oc0x pin output source. figure 13-4 shows a simplified schematic of the logic affected by the com0x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com0x1:0 bits are shown. when referring to the oc0x state, the reference is for the internal oc0x register, not the oc0x pin. if a system reset occur, the oc0x register is reset to ?0?. figure 13-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0x) from the waveform generator if either of the com0x1:0 bits are set. however, the oc0x pin direction (input or out- put) is still controlled by the da ta direction register (ddr) for th e port pin. the data direction register bit for the oc0x pin (ddr_oc0x) must be set as output before the oc0x value is visi- ble on the pin. the port override function is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc0x state before the out- put is enabled. note that some com0x1:0 bi t settings are reserved for certain modes of operation. see ?8-bit timer/counter register description? on page 102. port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focn clk i/o
96 7766f?avr?11/10 atmega16/32u4 13.5.1 compare output mode and waveform generation the waveform generator uses the com0x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com0x1:0 = 0 tells the waveform generator that no action on the oc0x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 13-2 on page 102 . for fast pwm mode, refer to table 13-3 on page 102 , and for phase correct pwm refer to table 13-4 on page 103 . a change of the com0x1:0 bits state will have effe ct at the first compare match after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the foc0x strobe bits. 13.6 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm02:0) and compare output mode (com0x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com0x1:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com0x1:0 bits control whether the output should be set, cleared, or toggled at a compare match ( see ?compare match output unit? on page 95. ). for detailed timing information see ?timer/counter timing diagrams? on page 100 . 13.6.1 normal mode the simplest mode of operation is the normal mode (wgm02:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal o peration the timer/counter overflow flag (tov0) will be set in the same timer clock cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 13.6.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm 02:0 = 2), the ocr0a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 13-5 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0a, and then counter (tcnt0) is cleared.
97 7766f?avr?11/10 atmega16/32u4 figure 13-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compar e match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com0a1:0 = 1). the oc0a value will not be visible on the port pin unless the data direction for the pin is set to output. the waveform ge nerated will have a ma ximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 13.6.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm02:0 = 3 or 7) provides a high fre- quency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to top then restarts from bot- tom. top is defined as 0xff when wgm2:0 = 3, and ocr0a when wgm2:0 = 7. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x, and set at bottom. in inverting compare output mode, the out- put is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac app lications. high frequency a llows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast tcntn ocn (toggle) ocnx interrupt flag set 1 4 period 2 3 (comnx1:0 = 1) f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------- - =
98 7766f?avr?11/10 atmega16/32u4 pwm mode is shown in figure 13-6 . the tcnt0 value is in the timing diagram shown as a his- togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal li ne marks on the tcnt0 slopes represent com- pare matches between ocr0x and tcnt0. figure 13-6. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches top. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a1:0 bits to one allows the oc0a pin to toggle on compare matches if th e wgm02 bit is set. this option is not available for the oc0b pin (see table 13-3 on page 102 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is gener- ated by setting (or clearing) the oc0x register at the compare match between ocr0x and tcnt0, and clearing (or setting) the oc0x regist er at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0a is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com0a1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting oc0x to toggle its logical level on each compare match (com0x1:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7 f ocnxpwm f clk_i/o n 256 ? ------------------ =
99 7766f?avr?11/10 atmega16/32u4 feature is similar to the oc0a toggle in ctc mode, except the double buffer feature of the out- put compare unit is enabled in the fast pwm mode. 13.6.4 phase correct pwm mode the phase correct pwm mode (wgm02:0 = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bot- tom. top is defined as 0xff when wgm2:0 = 1, and ocr0a when wgm2:0 = 5. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x while up counting, and set on the compare match while down- counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the sym- metric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. in phase correct pwm mode the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direction. the tcnt0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 13-7 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slop es represent compare matches between ocr0x and tcnt0. figure 13-7. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a0 bits to tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update
100 7766f?avr?11/10 atmega16/32u4 one allows the oc0a pin to toggle on compare ma tches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 13-4 on page 103 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm wave- form is generated by clearing (or setting) the oc0x register at the compare match between ocr0x and tcnt0 when the counter increments, and setting (or clearing) the oc0x register at compare match between ocr0x and tcnt0 when the counter decrements. the pwm fre- quency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0a is set equal to bottom, the output will be continuously low an d if set equal to max the output will be continuously high for non-inverted pwm mode. for in verted pwm the output will have the opposite logic values. at the very start of period 2 in figure 13-7 ocnx has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bot- tom. there are two cases that give a transition without compare match. ? ocr0a changes its value from max, like in figure 13-7 . when the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up- counting compare match. ? the timer starts counting from a value higher than the one in ocr0a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 13.7 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 13-8 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max val ue in all modes other than phase correct pwm mode. figure 13-8. timer/counter timing diagram, no prescaling figure 13-9 shows the same timing data, but with the prescaler enabled. f ocnxpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
101 7766f?avr?11/10 atmega16/32u4 figure 13-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) figure 13-10 shows the setting of ocf0b in all modes and ocf0a in all modes except ctc mode and pwm mode, where ocr0a is top. figure 13-10. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) figure 13-11 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode and fast pwm mode where ocr0a is top. figure 13-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
102 7766f?avr?11/10 atmega16/32u4 13.8 8-bit timer/counter register description 13.8.1 timer/counter control register a ? tccr0a ? bits 7:6 ? com01a:0: compare match output a mode these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0a pin must be set in order to enable the output driver. when oc0a is connected to the pin, the function of the com0a1:0 bits depends on the wgm02:0 bit setting. table 13-2 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 13-3 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97 for more details. bit 76543210 com0a 1 com0a 0 com0b 1 com0b 0 ?? wgm0 1 wgm0 0 tccr0a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 13-2. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 13-3. compare output mode, fast pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port op eration, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match, set oc0a at top 1 1 set oc0a on compare match, clear oc0a at top
103 7766f?avr?11/10 atmega16/32u4 table 13-4 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 99 for more details. ? bits 5:4 ? com0b1:0: compare match output b mode these bits control the output compare pin (oc0b) behavior. if one or both of the com0b1:0 bits are set, the oc0b output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0b pin must be set in order to enable the output driver. when oc0b is connected to the pin, the function of the com0b1:0 bits depends on the wgm02:0 bit setting. table 13-2 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 13-3 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97 for more details. table 13-4. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port op eration, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 10 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 11 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting. table 13-5. compare output mode, non-pwm mode com01 com00 description 0 0 normal port operation, oc0b disconnected. 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match table 13-6. compare output mode, fast pwm mode (1) com01 com00 description 0 0 normal port operation, oc0b disconnected. 01reserved 1 0 clear oc0b on compare match, set oc0b at top 1 1 set oc0b on compare match, clear oc0b at top
104 7766f?avr?11/10 atmega16/32u4 table 13-4 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 99 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits in the atmega 16u4/atmega32u4 and will always read as zero. ? bits 1:0 ? wgm01:0: waveform generation mode combined with the wgm02 bit found in the tccr0b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 13-8 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see ?modes of operation? on page 96 ). notes: 1. max = 0xff 2. bottom = 0x00 table 13-7. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0b disconnected. 01reserved 10 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting. 11 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting. table 13-8. waveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 10 0 1 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff top max 41 0 0reserved ? ? ? 51 0 1 pwm, phase correct ocra top bottom 61 1 0reserved ? ? ? 7 1 1 1 fast pwm ocra top top
105 7766f?avr?11/10 atmega16/32u4 13.8.2 timer/counter control register b ? tccr0b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0a bit, an immediate compare match is forced on the waveform generation unit. the oc0a output is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefore it is the value present in the com0a1:0 bits that determines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6 ? foc0b: force output compare b the foc0b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0b bit, an immediate compare match is forced on the waveform generation unit. the oc0b output is changed according to its com0b1:0 bits setting. note that the foc0b bit is implemented as a strobe. therefore it is the value present in the com0b1:0 bits that determines the effect of the forced compare. a foc0b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 3 ? wgm02: waveform generation mode see the description in the ?timer/counter control register a ? tccr0a? on page 102 . ? bits 2:0 ? cs02:0: clock select the three clock select bits select the clock source to be used by the timer/counter. bit 76543210 foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/write w w r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 13-9. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 001clk i/o /(no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler)
106 7766f?avr?11/10 atmega16/32u4 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 13.8.3 timer/counter register ? tcnt0 the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x registers. 13.8.4 output compare register a ? ocr0a the output compare register a contains an 8-bi t value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. 13.8.5 output compare register b ? ocr0b the output compare register b contains an 8-bi t value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0b pin. 13.8.6 timer/counter interrupt mask register ? timsk0 ? bits 7..3, 0 ? res: reserved bits these bits are reserved bits and will always read as zero. 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge. table 13-9. clock select bit description (continued) cs02 cs01 cs00 description bit 76543210 tcnt0 [7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0a [7:0] ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0b [7:0] ocr0b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543 2 10 ????? ocie0bocie0atoie0timsk0 read/writerrrrr r/wr/wr/w initial value00000 0 00
107 7766f?avr?11/10 atmega16/32u4 ? bit 2 ? ocie0b: timer/counter output compare match b interrupt enable when the ocie0b bit is written to one, and the i-bit in the status register is set, the timer/counter compare match b interrupt is enab led. the corresponding interrupt is executed if a compare match in timer/counter occurs, i.e., when the ocf0b bit is set in the timer/counter interrupt flag register ? tifr0. ? bit 1 ? ocie0a: timer/counter0 output compare match a interrupt enable when the ocie0a bit is written to one, and th e i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, i.e., when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and the i-bit in the status register is set, the timer/counter0 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter0 occurs, i.e., when the tov0 bit is set in the timer/counter 0 inter- rupt flag register ? tifr0. 13.8.7 timer/counter 0 interrupt flag register ? tifr0 ? bits 7..3, 0 ? res: reserved bits these bits are reserved bits in the atmega 16u4/atmega32u4 and will always read as zero. ? bit 2 ? ocf0b: timer/counter 0 output compare b match flag the ocf0b bit is set when a compare match occurs between the timer/counter and the data in ocr0b ? output compare register0 b. ocf0b is cleared by hardware when executing the cor- responding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0b (timer/counter compare b match interrupt enable), and ocf0b are set, the timer/counter compare match interrupt is executed. ? bit 1 ? ocf0a: timer/counter 0 output compare a match flag the ocf0a bit is set when a compare match occurs between the timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when executing the cor- responding interrupt handling vector. alternativel y, ocf0a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0a (timer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occurs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0 (timer/counter0 overflow interrupt enable), and tov0 are set, the timer/counter0 overflow interrupt is executed. the setting of this flag is dependent of the wgm02:0 bit setting. refer to table 13-8 , ?waveform generation mode bit description? on page 104 . bit 76543210 ?????ocf0bocf0a tov0 tifr0 read/writerrrrrr/wr/wr/w initial value00000000
108 7766f?avr?11/10 atmega16/32u4 14. 16-bit timers/counters (timer /counter1 and timer/counter3) the 16-bit timer/counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. the main features are: ? true 16-bit design (i.e., allows 16-bit pwm) ? three independent output compare units ? double buffered outp ut compare registers ? one input capture unit ? input capture noise canceler ? clear timer on compare match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? ten independent interrupt sources (tov1, ocf1a, ocf1b, ocf1c, icf1, tov3, ocf3a, ocf3b, ocf3c and icf3) 14.1 overview most register and bit references in this sect ion are written in general form. a lower case ?n? replaces the timer/counter number, and a) lower case ?x? replaces the output compare unit channel. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit timer/counter is shown in figure 14-1 . for the actual placement of i/o pins, see ?pinout atmega16u4/atmega32u4? on page 3 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?16-bit timers/counters (timer/counter1 and timer/counter3)? on page 108 . the power reduction timer/counter1 bit, prtim1, in ?power reduction register 0 - prr0? on page 46 must be written to zero to enable timer/counter1 module. the power reduction timer/counter3 bit, prtim3, in ?power reduction register 1 - prr1? on page 46 must be written to zero to enable timer/counter3 module.
109 7766f?avr?11/10 atmega16/32u4 figure 14-1. 16-bit timer/counter block diagram (1) note: 1. refer to ?pinout atmega16u4/atmega32u4? on page 3 , table 10-3 on page 72 , and table 10-6 on page 75 for timer/counter1 and 3 and 3 pin placement and description. 2. tn only refers to t1 since t3 input is not available on the atmega16u4/atmega32u4 product . 14.1.1 registers the timer/counter (tcntn), output compare registers (ocrna/b/c), and input capture reg- ister (icrn) are all 16-bit registers. special procedures must be followed when accessing the 16- bit registers. these procedures are described in the section ?accessing 16-bit registers? on page 110 . the timer/counter control registers (t ccrna/b/c) are 8-bit registers and have no cpu access restrictions. interrupt requests (short en as int.req.) signals are all visible in the timer interrupt flag register (t ifrn). all interrupts are individually masked with the timer inter- rupt mask register (timskn). tifrn and timskn are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the tn pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t n ). icfn (int.req.) tovn (int.req.) clock select timer/counter databus icrn = = = tcntn waveform generation waveform generation waveform generation ocna ocnb ocnc noise canceler icpn = fixed top values edge detector control logic = 0 top bottom count clear direction ocfna (int.req.) ocfnb (int.req.) ocfnc (int.req.) tccrna tccrnb tccrnc ( from analog comparator ouput ) tn edge detector ( from prescaler ) tclk ocrnc ocrnb ocrna (2)
110 7766f?avr?11/10 atmega16/32u4 the double buffered output compare registers (ocrna/b/c) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform gener- ator to generate a pwm or variable frequency output on the output compare pin (ocna/b/c). see ?output compare units? on page 117. . the compare match event will also set the compare match flag (ocfna/b/c) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/ counter value at a given external (edge trig- gered) event on either the input capture pin (icpn) or on the analog comparator pins ( see ?analog comparator? on page 289. ) the input capture unit includes a digital filtering unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocrna register, the icrn regist er, or by a set of fixed values. when using ocrna as top value in a pwm mode, the ocrna register can not be used for generating a pwm output. however, the top value will in this case be do uble buffered allowing the top value to be changed in run time. if a fixed top value is required, the icrn register can be used as an alternative, freeing the ocrna to be used as pwm output. 14.1.2 definitions the following definitions are used extensively throughout the document: 14.2 accessing 16-bit registers the tcntn, ocrna/b/c, and icrn are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write opera- tions. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16- bit access. the same temporary register is shared between all 16-bit registers within each 16- bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary regi ster for the high byte. reading the ocrna/b/c 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte. for a 16-bit read, the low byte must be read before the high byte. the following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocrna/b/c and icrn registers. note that when using ?c?, the compiler handles the 16-bit access. table 14-1. bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocrna or icrn register. the assignment is dependent of the mode of operation.
111 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. the assembly code example returns the tcntn value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer regis- ters, then the result of the a ccess outside the interrupt will be corrupted. theref ore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcntn register contents. reading any of the ocrna/b/c or icrn registers can be done by using the same principle. assembly code examples (1) ... ; set tcntn to 0x01ff ldi r17,0x01 ldi r16,0xff out tcntnh,r17 out tcntnl,r16 ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ... c code examples (1) unsigned int i; ... /* set tcntn to 0x01ff */ tcntn = 0x1ff; /* read tcntn into i */ i = tcntn; ...
112 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. the assembly code example returns the tcntn value in the r17:r16 register pair. assembly code example (1) tim16_readtcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcntn( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* read tcntn into i */ i = tcntn; /* restore global interrupt flag */ sreg = sreg; return i; }
113 7766f?avr?11/10 atmega16/32u4 the following code examples show how to do an atomic write of the tcntn register contents. writing any of the ocrna/b/c or icrn registers can be done by using the same principle. note: 1. see ?code examples? on page 8. the assembly code example requires that the r17:r16 register pair contains the value to be writ- ten to tcntn. 14.2.1 reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. 14.3 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (csn2:0) bits located in the timer/counter control register b (tccrnb). for details on clock sources and prescaler, see ?timer/counter0, timer/counter1, and timer/counter3 prescalers? on page 89 . assembly code example (1) tim16_writetcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcntn to r17:r16 out tcntnh,r17 out tcntnl,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcntn( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* set tcntn to i */ tcntn = i; /* restore global interrupt flag */ sreg = sreg; }
114 7766f?avr?11/10 atmega16/32u4 14.4 counter unit the main part of the 16-bit timer/counter is th e programmable 16-bit bi-directional counter unit. figure 14-2 shows a block diagram of the counter and its surroundings. figure 14-2. counter unit block diagram signal description (internal signals): count increment or decrement tcntn by 1. direction select between increment and decrement. clear clear tcntn (set all bits to zero). clk t n timer/counter clock. top signalize that tcntn has reached maximum value. bottom signalize that tcntn has re ached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcntnh) con- taining the upper eight bits of the counter, and counter low (tcntnl) containing the lower eight bits. the tcntnh register can only be indirect ly accessed by the cpu. when the cpu does an access to the tcntnh i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcntnh value when the tcntnl is read, and tcntnh is updated with the temporary register va lue when tcntnl is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are special cases of writing to the tcntn register when the counter is counting that will gi ve unpredictable results. the s pecial cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t n ). the clk t n can be generated from an external or internal clock source, selected by the clock select bits (csn2:0). when no clock source is selected (csn2:0 = 0) the timer is stopped. however, the tcntn value can be accessed by the cpu, independent of whether clk t n is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgmn3:0) located in the timer/counter control registers a and b (tccrna and tccrnb). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs ocnx. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 120 . temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear direction tovn (int.req.) clock select top bottom tn edge detector ( from prescaler ) clk tn
115 7766f?avr?11/10 atmega16/32u4 the timer/counter overflow flag (tovn) is set according to the mode of operation selected by the wgmn3:0 bits. tovn can be used for generating a cpu interrupt. 14.5 input capture unit the timer/counter incorporates an input capture un it that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or mul- tiple events, can be applied via the icpn pin or al ternatively, for the timer/counter1 only, via the analog comparator unit. the time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 14-3 . the elements of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 14-3. input capture unit block diagram note: the analog comparator output (aco) ca n only trigger the timer/counter1 icp ? not timer/counter3, 4 or 5. when a change of the logic level (an event) occurs on the input capture pin (icpn), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a capture will be triggered. when a captur e is triggered, the 16-bit value of the counter (tcntn) is written to the input capture register (icrn). the input capture flag (icfn) is set at the same system clock as the tcntn value is c opied into icrn register. if enabled (ticien = 1), the input capture flag generates an input capt ure interrupt. the icfn flag is automatically cleared when the interrupt is executed. alternativ ely the icfn flag can be cleared by software by writing a logical one to its i/o bit location. icfn (int.req.) analog comparator write icrn (16-bit register) icrnh (8-bit) noise canceler icpn edge detector temp (8-bit) data bus (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) acic* icnc ices aco*
116 7766f?avr?11/10 atmega16/32u4 reading the 16-bit value in the input capture register (icrn) is done by first reading the low byte (icrnl) and then the high byte (icrnh). when the low byte is read the high byte is copied into the high byte temporary register (temp). when the cpu reads the icrnh i/o location it will access the temp register. the icrn register can only be written when us ing a waveform generation mode that utilizes the icrn register for defining the counter?s top value. in these cases the waveform genera- tion mode (wgmn3:0) bits must be set before the top value can be written to the icrn register. when writing the icrn re gister the high byte must be written to the icrnh i/o location before the low byte is written to icrnl. for more information on how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 110 . 14.5.1 input capture trigger source the main trigger source for the input capture unit is the input capture pin (icpn). timer/counter1 can alternatively use the analog comparator output as trigger source for the input capture unit. the analog comparator is selected as trigger source by setting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a capture. the input capture flag must therefore be cleared after the change. both the input capture pin (icpn) and the analog comparator output (aco) inputs are sampled using the same technique as for the tn pin ( figure 12-1 on page 89 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases t he delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabl ed unless the timer/counter is set in a wave- form generation mode that uses icrn to define top. an input capture can be tri ggered by software by controllin g the port of the icpn pin. 14.5.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icncn) bit in timer/counter control register b (tccrnb). when enabled the noise canceler introduces addi- tional four system clock cycles of delay from a change applied to the input, to the update of the icrn register. the noise canceler uses the sy stem clock and is therefore not affected by the prescaler. 14.5.3 using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in th e icrn register before the nex t event occurs, the icrn will be overwritten with a new value. in this case the result of the ca pture will be incorrect. when using the input capture interrupt, the icrn register should be read as early in the inter- rupt handler routine as possible. even though the input capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests.
117 7766f?avr?11/10 atmega16/32u4 using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icrn register has been read. after a change of the edge, the input capture flag (icfn) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icfn flag is not required (if an interrupt handler is used). 14.6 output compare units the 16-bit comparator continuously compares tcntn with the output compare register (ocrnx). if tcnt equals ocrnx the comparator signals a match. a match will set the output compare flag (ocfnx) at the next timer clock cycle. if enabled (ocienx = 1), the output com- pare flag generates an output compare interrupt. the ocfnx flag is automatically cleared when the interrupt is executed. alternatively the ocfnx flag can be cleared by software by writ- ing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgmn3:0) bits and compare output mode (comnx1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( see ?modes of operation? on page 120. ) a special feature of output compare unit a allows it to define the timer/counter top value (i.e., counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 14-4 shows a block diagram of the output compare unit. the small ?n? in the register and bit names indicates the device number (n = n for timer/counter n), and the ?x? indicates output compare unit (a/b/c). the elements of the block diagram that are not directly a part of the out- put compare unit are gray shaded. figure 14-4. output compare unit, block diagram ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. (8-bit) ocnx temp (8-bit) data bus (8-bit) ocrnxl buf. (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) waveform generator top bottom
118 7766f?avr?11/10 atmega16/32u4 the ocrnx register is double buffered when using any of the twelve pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocrnx com- pare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the out- put glitch-free. the ocrnx register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocrnx buffer register, and if double buffering is dis- abled the cpu will access the ocrnx directly. the content of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as the tcnt1 and icr1 register). therefore ocr1x is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as when accessing other 16-bit registers. writing the ocrnx registers must be done via the temp reg- ister since the compare of all 16 bits is done continuously. the high byte (ocrnxh) has to be written first. when the high byte i/o location is written by the cpu, the temp register will be updated by the value written. then when the low by te (ocrnxl) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the ocrnx bu ffer or ocrnx compare register in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 110 . 14.6.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (focnx) bit. forcing compare match will not set the ocfnx flag or reload/clear the timer, but the ocnx pin will be updated as if a real compare match had occurred (the comn1:0 bits settings define whether the ocnx pin is set, cleared or toggled). 14.6.2 compare match bloc king by tcntn write all cpu writes to the tcntn register will block any compare match that o ccurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocrnx to be initialized to the same value as tcntn without triggering an inte rrupt when the timer/counter clock is enabled. 14.6.3 using the output compare unit since writing tcntn in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changing tcntn when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcntn equals the ocrnx value, the compare matc h will be missed, resulting in incorrect wave- form generation. do not write the tcntn equal to top in pwm modes with variable top values. the compare match for the top will be ignored and the counte r will continue to 0xffff. similarly, do not write the tcntn value equal to bottom when the counter is downcounting. the setup of the ocnx should be performed before setting the data direction register for the port pin to output. the easiest way of setting the ocnx value is to use the force output com- pare (focnx) strobe bits in normal mode. the ocnx register keeps its value even when changing between waveform generation modes. be aware that the comnx1:0 bits are not doubl e buffered together with the compare value. changing the comnx1:0 bits will take effect immediately.
119 7766f?avr?11/10 atmega16/32u4 14.7 compare match output unit the compare output mode (comnx1:0) bits have two functions. the waveform generator uses the comnx1:0 bits for defining the output compare (ocnx) state at the next compare match. secondly the comnx1:0 bits control the ocnx pin output source. figure 14-5 shows a simplified schematic of the logic affected by the comnx1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the comnx1:0 bits are shown. when referring to the ocnx state, the reference is for the internal ocnx register, not the ocnx pin. if a system reset occur, the ocnx register is reset to ?0?. figure 14-5. compare match output unit, schematic the general i/o port function is overridden by the output compare (ocnx) from the waveform generator if either of the comnx1:0 bits are set. however, the ocnx pin direction (input or out- put) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the ocnx pin (ddr_ocnx) must be set as output before the ocnx value is visi- ble on the pin. the port override function is generally independent of the waveform generation mode, but there are some exceptions. refer to table 14-2 , table 14-3 and table 14-4 for details. the design of the output compare pin logic allows initialization of the ocnx state before the out- put is enabled. note that some comnx1:0 bi t settings are reserved for certain modes of operation. see ?16-bit timers/counters (timer/counter1 and timer/counter3)? on page 108. the comnx1:0 bits have no effect on the input capture unit. 14.7.1 compare output mode and waveform generation the waveform generator uses the comnx1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the comnx1:0 = 0 tells the waveform generator that no action on the ocnx register is to be performed on the next compare match. for compare output actions in the port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
120 7766f?avr?11/10 atmega16/32u4 non-pwm modes refer to table 14-2 on page 130 . for fast pwm mode refer to table 14-3 on page 130 , and for phase correct and phase and frequency correct pwm refer to table 14-4 on page 131 . a change of the comnx1:0 bits st ate will have effect at the first compare matc h after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the focnx strobe bits. 14.8 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgmn3:0) and compare output mode (comnx1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the comnx1:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the comnx1:0 bits control whether the output should be set, cleared or toggle at a compare match ( see ?compare match output unit? on page 119. ) for detailed timing information refer to ?timer/counter timing diagrams? on page 127 . 14.8.1 normal mode the simplest mode of operation is the normal mode (wgmn3:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter overflow flag (tovn) will be set in the same timer clock cycle as the tcntn become s zero. the tovn flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tovn flag, the timer resolution can be increased by soft- ware. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generat e interrupts at some given time. using the output compare to gene rate waveforms in norm al mode is not recommended, since this will occupy too much of the cpu time. 14.8.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgmn3:0 = 4 or 12), the ocrna or icrn register are used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcntn) matches either the ocrna (wgmn3:0 = 4) or the icrn (wgmn3:0 = 12). the ocrna or icrn define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the opera- tion of counting external events. the timing diagram for the ctc mode is shown in figure 14-6 . the counter value (tcntn) increases until a compare match occurs with either ocrna or icrn, and then counter (tcntn) is cleared.
121 7766f?avr?11/10 atmega16/32u4 figure 14-6. ctc mode, timing diagram an interrupt can be generated at each time the counter value reaches the top value by either using the ocfna or icfn flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. how- ever, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buff- ering feature. if the new value written to ocrna or icrn is lower than the current value of tcntn, the counter will miss the co mpare match. the counter will then have to count to its max- imum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is no t desirable. an alternative will th en be to use the fast pwm mode using ocrna for defining top (w gmn3:0 = 15) since the ocrna then will be doub le buffered. for generating a waveform output in ctc mode, the ocna output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (comna1:0 = 1). the ocna value will not be visible on the port pin unless the data direction for the pin is set to output (ddr_ocna = 1). th e waveform generated will have a maximum fre- quency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tovn flag is set in the same timer clock cycle that the counter counts from max to 0x0000. 14.8.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgmn3:0 = 5, 6, 7, 14, or 15) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (ocnx) is set on the compare match between tcntn and ocrnx, and cleared at top. in inverting compare output mode output is cleared on compare match and set at top. due to the single-slope oper- ation, the operating frequency of the fast pwm mode can be twice as high as the phase correct and phase and frequency correct pwm modes that use dual-slope operation. this high fre- quency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically sm all sized external com ponents (coils, capaci- tors), hence reduces total system cost. tcntn ocna (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1) f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------- - =
122 7766f?avr?11/10 atmega16/32u4 the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the max- imum resolution is 16-bit (icrn or ocrna set to max). the pwm resolution in bits can be calculated by using the following equation: in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn3:0 = 5, 6, or 7), the value in icrn (wgmn3:0 = 14), or the value in ocrna (wgmn3:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 14-7 . the figure shows fast pwm mode when ocrna or icrn is us ed to define top. the tcntn value is in the timing diagram shown as a histogram for illu strating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matches between ocrnx and tcntn. the ocnx interrupt flag will be set when a compare match occurs. figure 14-7. fast pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches top. in addition the ocna or icfn flag is set at the same time r clock cycle as tovn is set when either ocrna or icrn is used for defining the top value. if one of the interrupts are enabled, the interrupt han- dler routine can be used for updating the top and compare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values the unused bits are masked to zero when any of the ocrnx registers are written. the procedure for updating icrn differs from updating ocrna when used for defining the top value. the icrn register is not double buffered. this means that if icrn is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icrn value written is lower than the current va lue of tcntn. the result will then be that the counter will miss the compare matc h at the top value. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. the ocrna register however, is double buffered. this feature allows the ocrna i/o location r fpwm top 1 + () log 2 () log ---------------------------------- - = tcntn ocrnx / top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
123 7766f?avr?11/10 atmega16/32u4 to be written anytime. when the ocrna i/o location is written the value written will be put into the ocrna buffer register. th e ocrna compare register will th en be updated with the value in the buffer register at the next timer clo ck cycle the tcntn matches top. the update is done at the same timer clock cycle as the tcnt n is cleared and the tovn flag is set. using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively change d (by changing the top value), using the ocrna as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the ocnx pins. setting the comnx1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to three (see table on page 130 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn, and clearing (or setting) the ocnx register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocrnx is set equal to bottom (0x0000) the out- put will be a narrow spike for eac h top+1 timer clock cycle. se tting the ocrnx equal to top will result in a const ant high or low output (depending on the polarity of the output set by the comnx1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting ocna to toggle its logical level on each compare match (comna1:0 = 1). this applies only if ocr1a is used to define the top value (wgm 13:0 = 15). the wave form generated will have a maximum frequency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). this feature is similar to the ocna toggle in ctc mode, except the double buffer feature of the output com- pare unit is enabled in the fast pwm mode. 14.8.4 phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgmn3:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a dual- slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feat ure of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- - =
124 7766f?avr?11/10 atmega16/32u4 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the pwm resolu- tion in bits can be calculated by using the following equation: in phase correct pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn3:0 = 1, 2, or 3), the value in icrn (wgmn3:0 = 10), or the value in ocrna (wgmn3:0 = 11). the counter has then reached the top and changes the count direct ion. the tcntn value will be equa l to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 14-8 . the figure shows phase correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing diagram shown as a histogram for illustrati ng the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matches between ocrnx and tcntn. the ocnx inter- rupt flag will be set when a compare match occurs. figure 14-8. phase correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches bottom. when either ocrna or icrn is used for defining the top value, the ocna or icfn flag is set accord- ingly at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values, the unus ed bits are masked to zero when any of the ocrnx registers are written. as the third period shown in figure 14-8 illustrates, changing the top actively while the timer/counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocrnx reg- r pcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx/top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tovn interrupt flag set (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
125 7766f?avr?11/10 atmega16/32u4 ister. since the ocrnx update occurs at top, the pwm period starts and ends at top. this implies that the length of the falling slope is determined by the previous top value, while the length of the rising slope is determined by th e new top value. when these two values differ the two slopes of the period will differ in length. the difference in length gives the unsymmetrical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the timer/counter is running. when using a static top value there are practically no differences between the two modes of operation. in phase correct pwm mode, the compare units allow generation of pwm waveforms on the ocnx pins. setting the comnx1:0 bits to tw o will produce a non-inverte d pwm and an inverted pwm output can be generated by setting the comnx1:0 to three (see table 14-4 on page 131 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is gene rated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn when the counter increments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted pwm mode. for in verted pwm the output will have the opposite logic values. if ocr1a is used to define the top value (wgm13:0 = 11) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 14.8.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct pwm mode (wgmn3:0 = 8 or 9) provides a high reso lution phase and frequency correct pwm wave- form generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation fre- quency compared to the single-slope operation. howe ver, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase correct, and the phase and frequency correct pwm mode is the time the ocrnx register is up dated by the ocrnx buffer register, (see figure 14- 8 and figure 14-9 ). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - =
126 7766f?avr?11/10 atmega16/32u4 the maximum resolution is 16-bit (icrn or ocrn a set to max). the pwm resolution in bits can be calculated using the following equation: in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icrn (wgmn3:0 = 8), or the value in ocrna (wgmn3:0 = 9). the counter has then reac hed the top and ch anges the count di rection. the tcntn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown on figure 14-9 . the figure shows phase and frequency correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing dia- gram shown as a histogram for illustrating the dual-slope operati on. the diagram includes non- inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes repre- sent compare matches between o crnx and tcntn. the ocnx inte rrupt flag will be set when a compare match occurs. figure 14-9. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at bottom). when either ocrna or icrn is used for defining the top value, the ocna or icfn flag set when tcntn has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will neve r occur between the tcntn and the ocrnx. as figure 14-9 shows the output generated is, in contrast to the phase correct mode, symmetri- cal in all periods. since the ocrnx registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. r pfcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx/top updateand tovn interrupt flag set (interrupt on bottom) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
127 7766f?avr?11/10 atmega16/32u4 using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively changed by changing the top value, using the ocrna as top is clearly a better choice due to its double buffer feature. in phase and frequency correct pwm mode, the compare units allow generation of pwm wave- forms on the ocnx pins. settin g the comnx1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to three (see table 14-4 on page 131 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn when the counter incre- ments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pw m frequency for the output when using phase and frequency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be set to high for non- inverted pwm mode. for in verted pwm the output will have the opposite lo gic values. if ocr1a is used to define the top va lue (wgm13:0 = 9) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 14.9 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk tn ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set, and when the ocrnx register is updated with the ocrnx buffer value (only for modes utilizing double buffering). figure 14-10 shows a timing diagram for the setting of ocfnx. figure 14-10. timer/counter timing diagram, setting of ocfnx, no prescaling figure 14-11 shows the same timing data, but with the prescaler enabled. f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - = clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2
128 7766f?avr?11/10 atmega16/32u4 figure 14-11. timer/counter timing diagram, setting of ocfnx, with prescaler (f clk_i/o /8) figure 14-12 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocrnx register is updated at bottom. the timing diagrams will be the same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tovn flag at bottom. figure 14-12. timer/counter timing diagram, no prescaling figure 14-13 shows the same timing data, but with the prescaler enabled. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o
129 7766f?avr?11/10 atmega16/32u4 figure 14-13. timer/counter timing dia gram, with prescaler (f clk_i/o /8) 14.10 16-bit timer/counter register description 14.10.1 timer/counter1 control register a ? tccr1a 14.10.2 timer/counter3 control register a ? tccr3a ? bit 7:6 ? comna1:0: compare output mode for channel a ? bit 5:4 ? comnb1:0: compare output mode for channel b ? bit 3:2 ? comnc1:0: compare output mode for channel c the comna1:0, comnb1:0, and comnc1:0 control the output compare pins (ocna, ocnb, and ocnc respectively) behavior. if one or both of the comna1:0 bits are written to one, the ocna output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the comnb1:0 bits are written to one, the ocnb output overrides the normal port func- tionality of the i/o pin it is connected to. if one or both of the comnc1:0 bits are written to one, the ocnc output overrides the normal port functionality of the i/o pin it is connected to. how- ever, note that the data direction register (ddr) bit corresponding to the ocna, ocnb or ocnc pin must be set in order to enable the output driver. tovn (fpwm) and icf n (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 76543210 com1a1 com1a0 com1b1 com1b0 co m1c1 com1c0 wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 com3a1 com3a0 com3b1 com3b0 co m3c1 com3c0 wgm31 wgm30 tccr3a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
130 7766f?avr?11/10 atmega16/32u4 when the ocna, ocnb or ocnc is connected to the pin, the function of the comnx1:0 bits is dependent of the wgmn3:0 bits setting. table 14-2 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to a normal or a ctc mode (non-pwm). table 14-3 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to the fast pwm mode. note: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1/comnc1 is set. in this case t he compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97. for more details. table 14-4 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to the phase correct and frequency correct pwm mode. table 14-2. compare output mode, non-pwm comna1/comnb1/ comnc1 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 01 toggle ocna/ocnb/ocnc on compare match. 10 clear ocna/ocnb/ocnc on compare match (set output to low level). 11 set ocna/ocnb/ocnc on compare match (set output to high level). table 14-3. compare output mode, fast pwm comna1/comnb1/ comnc0 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 01 wgm13:0 = 14 or 15: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other wgm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected. 10 clear ocna/ocnb/ocnc on compare match, set ocna/ocnb/ocnc at top 11 set ocna/ocnb/ocnc on compare match, clear ocna/ocnb/ocnc at top
131 7766f?avr?11/10 atmega16/32u4 note: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1//comnc1 is set. see ?phase correct pwm mode? on page 99. for more details. ? bit 1:0 ? wgmn1:0: waveform generation mode combined with the wgmn3:2 bits found in the tccrnb register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 14-5 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse width modulation (pwm) modes. ( see ?modes of operation? on page 96. ). table 14-4. compare output mode, phase correct and phase and frequency correct pwm comna1/comnb/ comnc1 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 01 wgm13:0 = 8, 9 10 or 11: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other wgm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected. 10 clear ocna/ocnb/ocnc on compare match when up-counting. set ocna/ocnb/ocnc on compare match when downcounting. 11 set ocna/ocnb/ocnc on compare match when up-counting. clear ocna/ocnb/ocnc on compare match when downcounting. table 14-5. waveform generation mode bit description (1) mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation top update of ocrn x at tovn flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocrna immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff top top 6 0 1 1 0 fast pwm, 9-bit 0x01ff top top 7 0 1 1 1 fast pwm, 10-bit 0x03ff top top 8 1 0 0 0 pwm, phase and frequency correct icrn bottom bottom 9 1 0 0 1 pwm, phase and frequency correct ocrna bottom bottom 10 1 0 1 0 pwm, phase correct icrn top bottom 11 1 0 1 1 pwm, phase correct ocrna top bottom 12 1 1 0 0 ctc icrn immediate max
132 7766f?avr?11/10 atmega16/32u4 note: 1. the ctcn and pwmn1:0 bit defi nition names are obsolete. use the wgm n2:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. 14.10.3 timer/counter1 control register b ? tccr1b 14.10.4 timer/counter3 control register b ? tccr3b ? bit 7 ? icncn: input capture noise canceler setting this bit (to one) activates the input ca pture noise canceler. when the noise canceler is activated, the input from the input capture pin (icpn) is filtered. the filter function requires four successive equal valued samples of the icpn pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 6 ? icesn: input capture edge select this bit selects which edge on the input capture pin (icpn) that is used to trigger a capture event. when the icesn bit is written to zero, a falling (negative) edge is used as trigger, and when the icesn bit is written to one, a risi ng (positive) edge w ill trigger the capture. when a capture is triggered according to the icesn setting, the counter value is copied into the input capture register (icrn). the event will also set the input capture flag (icfn), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icrn is used as top value (see description of the wgmn3:0 bits located in the tccrna and the tccrnb register), the icpn is disconnected and consequently the input cap- ture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future de vices, this bit must be written to zero when tccrnb is written. ? bit 4:3 ? wgmn3:2: waveform generation mode see tccrna register description. ? bit 2:0 ? csn2:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 13-8 and figure 13-9 . 13 1 1 0 1 (reserved) ? ? ? 14 1 1 1 0 fast pwm icrn top top 15 1 1 1 1 fast pwm ocrna top top table 14-5. waveform generation mode bit description (continued) (1) mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation top update of ocrn x at tovn flag set on bit 76543210 icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icnc3 ices3 ? wgm33 wgm32 cs32 cs31 cs30 tccr3b read/write r/w r/w r r/w r/w r/w r/w r/w initial value00000000
133 7766f?avr?11/10 atmega16/32u4 if external pin modes are used for the timer/countern, transitions on the tn pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 14.10.5 timer/counter1 control register c ? tccr1c 14.10.6 timer/counter3 control register c ? tccr3c ? bit 7 ? focna: force output compare for channel a the focna/focnb/focnc bits are only active when the wgmn3:0 bits specifies a non-pwm mode. when writing a logical one to the fo cna/focnb/focnc bit, an immediate compare match is forced on the waveform generation unit. the ocna/ocnb/ocnc output is changed according to its comnx1:0 bits setting. note that the focna/focnb/focnc bits are imple- mented as strobes. therefore it is the value present in the comnx1:0 bits that determine the effect of the forced compare. a focna/focnb/focnc strobe will no t generate any interrupt nor w ill it clear the timer in clear timer on compare match (ctc) mode using ocrna as top. the focna/focnb/focnb bits are always read as zero. ? bit 4:0 ? reserved bits these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be written to zero when tccrnc is written. table 14-6. clock select bit description csn2 csn1 csn0 description 0 0 0 no clock source. (timer/counter stopped) 001clk i/o /1 (no prescaling 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on tn pin. clock on falling edge 1 1 1 external clock source on tn pin. clock on rising edge bit 7654 3 210 foc1a foc1b foc1c ? ? ? ? ? tccr1c read/write w w w r r r r r initial value 0 0 0 0 0 0 0 0 bit 7654 3 210 foc3a??? ? ???tccr3c read/writewrrr r rrr initial value 0 0 0 0 0 0 0 0
134 7766f?avr?11/10 atmega16/32u4 14.10.7 timer/counter1 ? tcnt1h and tcnt1l 14.10.8 timer/counter3 ? tcnt3h and tcnt3l the two timer/counter i/o locations (tcntnh and tcntnl , combined tcntn) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is perfo rmed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. modifying the counter (tcntn) while the counte r is running introduces a risk of missing a com- pare match between tcntn and one of the ocrnx registers. writing to the tcntn register blocks (removes) the compare match on the following timer clock for all compare units. 14.10.9 output compare register 1 a ? ocr1ah and ocr1al 14.10.10 output compare register 1 b ? ocr1bh and ocr1bl 14.10.11 output compare register 1 c ? ocr1ch and ocr1cl bit 76543210 tcnt1[15:8] tcnt1h tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 tcnt3[15:8] tcnt3h tcnt3[7:0] tcnt3l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1a[15:8] ocr1ah ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1b[15:8] ocr1bh ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1c[15:8] ocr1ch ocr1c[7:0] ocr1cl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
135 7766f?avr?11/10 atmega16/32u4 14.10.12 output compare register 3 a ? ocr3ah and ocr3al 14.10.13 output compare register 3 b ? ocr3bh and ocr3bl 14.10.14 output compare register 3 c ? ocr3ch and ocr3cl the output compare registers contain a 16-bit value that is continuously compared with the counter value (tcntn). a match can be used to generate an output compare interrupt, or to generate a waveform output on the ocnx pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cp u writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. 14.10.15 input capture register 1 ? icr1h and icr1l 14.10.16 input capture register 3 ? icr3h and icr3l the input capture is updated with the counter (tcntn) value each time an event occurs on the icpn pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these regi sters, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. bit 76543210 ocr3a[15:8] ocr3ah ocr3a[7:0] ocr3al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr3b[15:8] ocr3bh ocr3b[7:0] ocr3bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr3c[15:8] ocr3ch ocr3c[7:0] ocr3cl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icr1[15:8] icr1h icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icr3[15:8] icr3h icr3[7:0] icr3l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
136 7766f?avr?11/10 atmega16/32u4 14.10.17 timer/counter1 interrupt mask register ? timsk1 14.10.18 timer/counter3 interrupt mask register ? timsk3 ? bit 5 ? icien: timer/countern, input capture interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern input capture interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 61. ) is executed when the icfn flag, located in tifrn, is set. ? bit 3 ? ocienc: timer/countern, output compare c match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare c match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 61. ) is executed when the ocfnc flag, located in tifrn, is set. ? bit 2 ? ocienb: timer/countern, output compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare b match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 61. ) is executed when the ocfnb flag, located in tifrn, is set. ? bit 1 ? ociena: timer/countern, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare a match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 61. ) is executed when the ocfna flag, located in tifrn, is set. ? bit 0 ? toien: timer/countern, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern overflow interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 61. ) is executed when the tovn flag, located in tifrn, is set. 14.10.19 timer/counter1 interr upt flag register ? tifr1 bit 7 6 5 4 3 2 1 0 ? ?icie1 ? ocie1c ocie1b ocie1a toie1 timsk1 read/write r r r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ?icie3 ? ocie3c ocie3b ocie3a toie3 timsk3 read/write r r r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ?icf1 ? ocf1c ocf1b ocf1a tov1 tifr1 read/write r r r/w r r/w r/w r/w r/w initial value00000000
137 7766f?avr?11/10 atmega16/32u4 14.10.20 timer/counter3 interr upt flag register ? tifr3 ? bit 5 ? icfn: timer/count ern, input capture flag this flag is set when a capture event occurs on the icpn pin. when the input capture register (icrn) is set by the wgmn3:0 to be used as the top value, the icfn flag is set when the coun- ter reaches the top value. icfn is automatically cleared when the input capt ure interrupt vector is executed. alternatively, icfn can be cleared by writing a logic one to its bit location. ? bit 3? ocfnc: timer/countern, output compare c match flag this flag is set in the timer clock cycle af ter the counter (tcntn) value matches the output compare register c (ocrnc). note that a forced output compare (foc nc) strobe will not set the ocfnc flag. ocfnc is automatically cleared when the output compare match c interrupt vector is exe- cuted. alternatively, ocfnc can be cleared by writing a logic one to its bit location. ? bit 2 ? ocfnb: timer/counter1, output compare b match flag this flag is set in the timer clock cycle af ter the counter (tcntn) value matches the output compare register b (ocrnb). note that a forced output compare (foc nb) strobe will not set the ocfnb flag. ocfnb is automatically cleared when the output compare match b interrupt vector is exe- cuted. alternatively, ocfnb can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle after the counter (tcntn value matches the output com- pare register a (ocrna). note that a forced output compare (foc na) strobe will not set the ocfna flag. ocfna is automatically cleared when the output compare match a interrupt vector is exe- cuted. alternatively, ocfna can be cleared by writing a logic one to its bit location. ? bit 0 ? tovn: timer/countern, overflow flag the setting of this flag is dependent of the wgmn3:0 bits setting. in normal and ctc modes, the tovn flag is set when the timer overflows. refer to table 14-5 on page 131 for the tovn flag behavior when using another wgmn3:0 bit setting. tovn is automatically cleared when the timer/countern overflow interrupt vector is executed. alternatively, tovn can be cleared by writing a logic one to its bit location. bit 76543210 ? ?icf3 ? ocf3c ocf3b ocf3a tov3 tifr3 read/write r r r/w r r/w r/w r/w r/w initial value00000000
138 7766f?avr?11/10 atmega16/32u4 15. 10-bit high speed timer/counter4 15.1 features ? up to 10-bit accuracy ? three independent output compare units ? clear timer on compare match (auto reload) ? glitch free, phase and frequency co rrect pulse width modulator (pwm) ? enhanced pwm mode: one optional additional accuracy bit without effect on output frequency ? variable pwm period ? independent dead time generators for each pwm channels ? synchronous update of pwm registers ? five independent interrupt sources (tov4, ocf4a, ocf4b, ocf4d, fpf4) ? high speed asynchronous and synchronous clocking modes ? separate prescaler unit 15.2 overview timer/counter4 is a general purpose high speed timer/counter module, with three independent output compare units, and with enhanced pwm support. the timer/counter4 features a high resolution and a high accuracy usage with the lower pres- caling opportunities. it can also support three accurate and high speed pulse width modulators using clock speeds up to 64 mhz. in pwm mode timer/counter4 and the output compare regis- ters serve as triple stand-alone pwms with non-overlapping, non-inverted and inverted outputs. the enhanced pwm mode allows to get one more accuracy bit while keeping the frequency identical to normal mode (a pwm 8 bits accuracy in enhanced mode outputs the same fre- quency that a pwm 7 bits accuracy in normal mode). similarly, the high prescaling opportunities make this unit useful for lower speed functions or exact timing functions with infrequent actions. a lock feature allows user to update the pwm registers and a simplified block diagram of the timer/counter4 is shown in figure 15-1 . for actual placement of the i/o pins, refer to ?pinout atmega16u4/atmega32u4? on page 3 . the device-specific i/o register and bit locations are listed in the ?register description? on page 162 .
139 7766f?avr?11/10 atmega16/32u4 figure 15-1. timer/counter4 block diagram 15.2.1 speed the maximum speed of the timer/counter4 is 64 mhz. however, if a supply voltage below 4 volts is used, it is recommended to decrease the input frequency, because the timer/counter4 is not running fast enough on low voltage levels. 15.2.2 accuracy the timer/counter4 is a 10-bit timer/counter modu le that can alternatively be used as an 8-bit timer/counter. the timer/counter4 registers are bas ically 8-bit registers, but on top of that there is a 2-bit high byte register (tc4h) that can be used as a common temporary buffer to access the two msbs of the 10-bit timer/counte r4 registers by the avr cpu via the 8-bit data bus, if the 10-bit accuracy is used. whereas, if the two msbs of the 10-bit registers are written to zero the timer/counter4 is working as an 8-bit timer/counter. when reading the low byte of any 8-bit register the two msbs are written to the tc4h register, and when writing the low byte of any 8-bit register the two msbs are written from the tc4h register. special procedures must be followed when accessing the 10-bit timer/counte r4 values via the 8-bi t data bus. these proce- dures are described in the section ?accessing 10-bit registers? on page 159 . the enhanced pwm mode allows to add a resolution bit to each compare register a/b/d, while the output frequency remains identical to a normal pwm mode. that means that the tc4h reg- ister contains one more bit that will be the m sb in a 11-bits enhanced pwm operation. see the section ?enhanced compare/pwm mode? on page 148 for details about this feature and how to use it. 8-bit databus t/c int. flag register (tifr4) 10-bit comparator 8-bit output compare register a (ocr4a) t/c int. mask register (timsk4) timer/counter4 (tcnt4) direction timer/counter4 control logic ocf4b tov4 toie4 ocie4b ocie4a ocf4a tov4 ocf4b oc4a ocf4a t/c control register a (tccr4a) com4b1 pwm4a pwm4b com4b0 foc4a foc4b 10-bit comparator 8-bit output compare register b (ocr4b) com4a1 com4a0 t/c control register b (tccr4b) cs42 psr4 cs41 cs40 cs43 oc4a oc4b oc4b dead time generator dead time generator 10-bit comparator 8-bit output compare register c (ocr4c) 10-bit comparator 8-bit output compare register d (ocr4d) com4a1 pwm4d com4a0 foc4d t/c control register c (tccr4c) ocf4d ocf4d ocie4d oc4d oc4d dead time generator psr4 psr4 ocw4a ocw4b ocw 4d 2-bit high byte register (tc4h) wgm41 fpen4 t/c control register d (tccr4e) com4b1 com4b0 com4d1 com4d0 fpnc4 fpes4 fpac4 10-bit output compare register b 10-bit output compare register c 10-bit output compare register d 10-bit output compare register a clear count clk t/c control register c (tccr4d) fault_protection wgm40 fpie4 fpf4 oc4oe5 oc4oe4 oc4oe3 oc4oe2 oc4oe1 oc4oe0 fpie4 fpf4
140 7766f?avr?11/10 atmega16/32u4 15.2.3 registers the timer/counter (tcnt4) and output compare registers (ocr4a, ocr4b, ocr4c and ocr4d) are 8-bit registers that are used as a data source to be compared with the tcnt4 con- tents. the ocr4a, ocr4b and ocr4d registers determine the action on the oc4a, oc4b and oc4d pins and they can also generate the co mpare match interrupts. the ocr4c holds the timer/counter top value, i.e. the clear on compare match value. t he timer/counter4 high byte register (tc4h) is a 2-bit register that is used as a comm on temporary buffer to access the msb bits of the timer/counter4 regist ers, if the 10-bit accuracy is used. interrupt request (overflow tov4, compare matches ocf4a, ocf4b, ocf4d and fault protec- tion fpf4) signals are visible in the timer interrupt flag register (tifr4) and timer/counter4 control register d (tccr4d). the interrupts are individually masked with the timer interrupt mask register (timsk4) and the fpie4 bit in the timer/counter4 control register d (tccr4d). control signals are found in the timer/counter control regi sters tccr4a, tccr4b, tccr4c, tccr4d and tccr4e. 15.2.4 synchronization in asynchronous clocking mode the timer/counter4 and the prescaler allow running the cpu from any clock source while the prescaler is opera ting on the fast peripheral clock (pck) having frequency up to 64 mhz. this is possible because there is a synchronization boundary between the cpu clock domain and the fast peripheral clock domain. figure 15-2 shows timer/counter 4 synchronization register block diagram and descr ibes synchronization delays in between regis- ters. note that all clock gating details are not shown in the figure. the timer/counter4 register values go through the internal synchronization registers, which cause the input synchronization delay, before af fecting the counter operation. the registers tccr4a, tccr4b, tccr4c, tccr4d, ocr4a, ocr4b, ocr4c and ocr4d can be read back right after writing the register. the read back values are delayed for the timer/counter4 (tcnt4) register, timer/counter4 high byte register (tc4h) and flags (ocf4a, ocf4b, ocf4d and tov4), because of the input and output synchronization. the system clock frequency must be lower than half of the pc k frequency, because the syn- chronization mechanism of the asynchronous time r/counter4 needs at least two edges of the pck when the system clock is high . if the frequency of th e system clock is too high, it is a risk that data or control values are lost.
141 7766f?avr?11/10 atmega16/32u4 figure 15-2. timer/counter4 synchronization register block diagram. 15.2.5 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output com- pare unit, in this case compare unit a, b, c or d. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt4 for accessing timer/counter4 counter value and so on. the definitions in table 15-1 are used extensively throughout the document. 8-bit databus ocr4a ocr4a_si tcnt4_so ocr4b ocr4b_si ocr4c ocr4c_si tccr4a tccr4a_si tccr4b tccr4b_si tcnt4 tcnt4_si ocf4a ocf4a_si ocf4b ocf4b_si tov4 tov4_si tov4_so ocf4b_so ocf4a_so tcnt4 s a s a plltm1:0 != '00' ck pck (clk tmr ) io-registers input synchronization registers timer/counter4 output synchronization registers sync mode async mode 1 ck delay 1/2 ck delay ~1/2 ck delay 1 pck delay 1 pck delay ~1 ck delay tcnt4 ocf4 ocf4b tov4 1/2 ck delay 1 ck delay ocr4d ocr4d_si tc4h tc4h_si tccr4c tccr4c_si tccr4d ocf4d ocf4d_si ocf4d_so ocf4d tc4h_so tc4h tccr4d_si table 15-1. definitions bottom the counter reaches the bottom when it becomes 0. max the counter reaches its maximum val ue when it becomes 0x3ff (decimal 1023). top the counter reaches the top value (stored in the ocr1c) when it becomes equal to the highest value in the count sequence. the top has a value 0x0ff as default after reset.
142 7766f?avr?11/10 atmega16/32u4 15.3 counter unit the main part of the timer/counter4 is the programmable bi-directional counter unit. figure 15- 3 shows a block diagram of the counter and its surroundings. figure 15-3. counter unit block diagram signal description (internal signals): count tcnt4 increment or decrement enable. direction select between increment and decrement. clear clear tcnt4 (set all bits to zero). clk t n timer/counter clock, referred to as clk t4 in the following. top signalize that tcnt4 has reached maximum value. bottom signalize that tcnt4 has re ached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t4 ). the timer clock is generated from an synchronous system clock or an asynchronous pll clock using the clock select bits (cs4<3:0>) and the pll postscaler for high speed timer bits (plltm1:0). when no clock sour ce is selected (cs4<3:0> = 0) the timer is stopped. however, the tcnt4 value can be accessed by the cpu, regardless of whether clk t1 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence of the timer/counter4 is determined by the setting of the wgm10 and pwm4x bits located in the timer/counter4 control re gisters (tccr4a, tccr4c and tccr4d). for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 149 . the timer/counter overflow flag (tov4) is set according to the mode of operation selected by the pwm4x and wgm40 bits. the overflow flag can be used for generating a cpu interrupt. 15.3.1 counter initialization for asynchronous mode to change timer/counter4 to the asynchronous mode follow the procedure below: 1. enable pll. 2. wait 100s for pll to stabilize . 3. poll the plock bit until it is set. 4. configure the plltm1:0 bits in the pllfrq register to enable the asynchronous mode (different from 0:0 value). data b u s tcnt4 control logic count tov4 top timer/counter4 count enable ( from prescaler ) bottom direction clear pck ck plltm1:0 clk t4
143 7766f?avr?11/10 atmega16/32u4 15.4 output compare unit the comparator continuously compares tcnt4 with the output compare registers (ocr4a, ocr4b, ocr4c and ocr4d). whenever tcnt4 equals to the output compare register, the comparator signals a match. a match will set the output compare flag (ocf4a, ocf4b or ocf4d) at the next timer clock cycle. if the corresponding interrupt is enabled, the output com- pare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is executed. alternativel y, the flag can be cleared by software by writ- ing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the pwm4x, wgm40 and compare out- put mode (com4x1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( see ?modes of operation? on page 149. ). figure 15-4 shows a block diagram of the output compare unit. figure 15-4. output compare unit, block diagram the ocr4x registers are double buffered when using any of the pulse width modulation (pwm) modes. for the normal mode of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr4x compare registers to either top or bottom of the counting sequence. the synchronization pr events the occurrence of odd-length, non-sym- metrical pwm pulses, thereby making the output glitch-free. see figure 15-5 for an example. during the time between the write and the update operation, a read from ocr4a, ocr4b, ocr4c or ocr4d will read the contents of the temporary location. this means that the most recently written value always will read out of ocr4a, ocr4b, ocr4c or ocr4d. ocfn x (int.req.) = (10-bit comparator ) 8-bit data bus tcntn wgmn0 waveform generator comnx1:0 pwmnx tcnh ocwnx 10-bit tcntn 10-bit ocrnx ocrnx focn top bottom
144 7766f?avr?11/10 atmega16/32u4 figure 15-5. effects of unsynchronized ocr latching 15.4.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force outp ut compare (foc4x) bit. forcin g compare match will not set the ocf4x flag or reload/cle ar the timer, but the wa veform output (ocw4x) will be updated as if a real compare match had occurred (the com4x1:0 bits settings define whether the waveform output (ocw4x) is set, cleared or toggled). 15.4.2 compare match bloc king by tcnt4 write all cpu write operations to the tcnt4 register will block any compare ma tch that occur in the next timer clock cycle, even when the timer is st opped. this feature allows ocr4x to be initial- ized to the same value as tcnt4 without triggering an interrupt when the timer/counter clock is enabled. 15.4.3 using the output compare unit since writing tcnt4 in any mode of operatio n will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt4 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tcnt4 equals the ocr4x value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write the tcnt4 value equal to bottom when the counter is down-counting. the setup of the waveform output (ocw4x) should be performed before setting the data direc- tion register for the port pin to output. the easiest way of setting the ocw4x value is to use the force output compare (foc4x) strobe bits in normal mode. the oc4x keeps its value even when changing between waveform generation modes. be aware that the com4x1:0 bits are not double buffered together with the compare value. changing the com4x1:0 bits will take effect immediately. output compare waveform ocwnx output compare wafeform ocwnx unsynchronized wfnx latch synchronized wfnx latch counter value compare value counter value compare value compare value changes glitch compare value changes
145 7766f?avr?11/10 atmega16/32u4 15.5 dead time generator the dead time generator is provided for the timer/counter4 pwm output pairs to allow driving external power control switches safely. the dead time generator is a separate block that can be used to insert dead times (non-overlapping times) for the timer/counter4 complementary output pairs oc4x and oc4x when the pwm mode is enabled and the com4x1:0 bits are set to ?01?. the sharing of tasks is as follows: the waveform generator generates the waveform out- put (ocw4x) and the dead time generator gener ates the non-overlapping pwm output pair from the waveform output. three dead time generators are provided, one for each pwm out- put. the non-overlap time is adjustable and the pwm output and it?s complementary output are adjusted separately, and independently for both pwm outputs. figure 15-6. output compare unit, block diagram the dead time generation is based on the 4- bit down counters that count the dead time, as shown in figure 15-7 . there is a dedicated prescaler in front of the dead time generator that can divide the timer/counter4 clock (pck or ck) by 1, 2, 4 or 8. this provides for large range of dead times that can be generated. the prescaler is controlled by two control bits dtps41..40. the block has also a rising and falling edge detector that is us ed to start the dea d time counting period. depending on the edge, one of the transitions on the rising edges, oc4x or oc4x is delayed until the counter has counted to zero. the comparator is used to compare the counter with zero and stop the dead time insertion when zero has been reached. the counter is loaded with a 4-bit dt4h or dt4l value from dt4 i/o register, depending on the edge of the waveform output (ocw4x) when the dead time insertion is started. the output compare output are delayed by one timer clock cycle at minimum from the waveform output when the dead time is adjusted to zero. the outputs oc4x and oc4x are inverted, if the pwm inversion mode bit pwm4x is set. this will also cause both outputs to be high during the dead time. figure 15-7. dead time generator ocnx pin wgmn0 waveform generator top focn comnx bottom pwmnx ocwnx dead time generator ocnx pin dtnh dtnl dtpsn ck or pck clock ocnx ocnx clock control ocnx ocnx ck or pck clock ocwnx 4-bit counter comparator dtnl dtnh dead time pre-scaler dtpsn dtn i/o register data bus (8-bit) tccrnb register pwmnx pwmnx
146 7766f?avr?11/10 atmega16/32u4 the length of the counting period is user adjustable by selecting the dead time prescaler setting by using the dtps41:40 control bits, and selecting then the dead time value in i/o register dt4. the dt4 register consists of tw o 4-bit fields, dt4h and dt4l that control the dead time periods of the pwm output and its' complementary output separately in terms of the number of pres- caled dead time ge nerator clock cycles. thus the rising edge of oc4x and oc4x can have different dead time periods as the t non-overlap / rising edge is adjusted by the 4-bit dt4h value and the t non-overlap / falling edge is adjusted by the 4-bit dt4l value. figure 15-8. the complementary output pair, com4x1:0 = 1 15.6 compare match output unit the compare output mode (com4x1:0) bits have two functions. the waveform generator uses the com4x1:0 bits for defining the inverted or non-inverted waveform output (ocw4x) at the next compare match. also, the com4x1:0 bits control the oc4x and oc4x pin output source. figure 15-9 shows a simplified schematic of the logic affected by the com4x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com4x1:0 bits are shown. in normal mode (non-pwm) the dead time genera tor is disabled and it is working like a syn- chronizer: the output compare (oc4x) is delayed from the waveform output (ocw4x) by one timer clock cycle. whereas in fast pwm mode and in phase and frequency correct pwm mode when the com4x1:0 bits are set to ?01? both the non-inverted and the inverted output compare output are generated, and an user programmable dead time delay is inserted for these complementary output pairs (oc4x and oc4x ). the functionality in pwm modes is similar to normal mode when any other com4x1:0 bit setup is used. when referring to the oc4x state, the reference is for the output compare output (oc4x) from the dead time generator, not the oc4x pin. if a system reset occur, the oc4x is reset to ?0?. the general i/o port function is overridden by the output compare (oc4x / oc4x ) from the dead time generator if either of the com4x1:0 bits are set. however, the oc4x pin direction (input or output) is still controlled by the data di rection register (ddr) fo r the port pin. the data direction register bit for the oc4x and oc4x pins (ddr_oc4x and ddr_oc4x) must be set as output before the oc4x and oc4x values are visible on the pin. the port override function is independent of the output compare mode. the design of the output compare pin configuration logic allows initialization of the oc4x state before the output is enabled. note that some com4x1:0 bit settings are reserved for certain modes of operation. for output compare pin configurations refer to table 15-2 on page 151 , table 15-3 on page 152 , table 15-4 on page 154 , and table 15-5 on page 155 . ocnx (comnx = 1) t non-overlap / rising edge t non-overlap / falling edge ocnx ocwnx
147 7766f?avr?11/10 atmega16/32u4 figure 15-9. compare match output unit, schematic 15.6.1 compare output mode and waveform generation the waveform generator uses the com4x1:0 bits differently in normal mode and pwm modes. for all modes, setting the com4x1:0 = 0 tells the waveform generator that no action on the ocw4x output is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 15-6 on page 162 . for fast pwm mode, refer to table 15-7 on page 162 , and for the phase and frequency correct pwm refer to table 15-8 on page 163 . a change of the com4x1:0 bits state will have effe ct at the first compare match after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the foc4x strobe bits. data bus portc6 ddrc6 dq ddrc7 portc7 dq dq dq clk i/o portb5 ddrb5 d q ddrb6 portb6 d q d q d q portd6 ddrd6 dq ddrd7 portd7 dq dq dq 1 0 1 0 oc4d pin 2 1 0 dead time generator d q q ocw4d clk tn oc4d pin output compare pin configuration com4d1:0 wgm41 oc4oe5:4 1 0 1 0 1 0 oc4b pin 2 1 0 dead time generator b q q ocw4b clk tn oc4b pin output compare pin configuration com4b1:0 wgm41 oc4oe3:2 1 0 1 0 oc4a pin 0 1 dead time generator a q q ocw4a clk tn oc4a pin output compare pin configuration com4a1:0 wgm41 oc4oe1:0 1 0 oc4a oc4a oc4b oc4b oc4 oc4d
148 7766f?avr?11/10 atmega16/32u4 15.6.2 enhanced compare/pwm mode when the bit enhc4 of tccr4e register is set, the enhanced compare/pwm mode is enabled. this mode allows user to add an accuracy bit to output compare register ocr4a, ocr4b and ocr4d. like explained previously, a compare condition appears when one of the three output compare registers (ocr4a/b/d) matches the value of tcnt4 (10-bits resolution). in basic pwm mode, the corresponding enabled output toggles on the compare match. the enhanced compare/pwm mode introduces a bit that determines on which internal clock edge the com- pare match condition is actually signalled. that means that th e corresponding outputs will toggle on the standard clock edge (like in normal mode) if the lsb of ocr4a/b/d is ?0?, or on the oppo- site (next) edge if the lsb is ?1?. user will notice that between normal and enhanced pwm modes, the output frequency will be identical, while the pwm resolution will be better in second case. writing to the output compare registers ocr4a/b/d or reading them will be identical in both modes. in enhanced mode, user must just consider that the tc4h register can be up to 3-bits wide (and have the same behavior than during 2-bits operation). that will concern ocr4a, ocr4b and ocr4d registers accesses only. indeed, the ocr4c register must not include the additional accuracy bit, and remains in the resolution that determines the output signal period. figure 15-10. how register access wo rks in enhanced mode that figure shows that the true ocr4a/b/d value corresponds to the value loaded by the user shifted on the right in order to transfer the least significant bit directly to the waveform genera- tion module. the maximum available resolution is 11-bits, but any other resolution can be specified. for example, a 8-bits resolution will allow to obtain the same frequency than a normal pwm mode with 7-bits resolution. example: ? pll postcaler output = 64 mhz, no prescaler on timer/counter4. ? setting ocr4c = 0x7f determines a full 7-bits theoretical resolution, and so a 500khz output frequency. 9 6 3 1 5 7 420 8 10 9 6 3 1 5 7 420 8 (tc4h) (ocr4a/b/d) output compare module a/b/d waveform generation enhanced mode pin toggle true ocr4a/b/d user interface side timer logic side enhc4 tcnt4<9:0> ocr4c<9:0> configuration bits (lsb)
149 7766f?avr?11/10 atmega16/32u4 ? setting ocr4a = 0x85 (= b?10000101?) signifies that the true value of ?compare a? register is 0x42 (b?01000010?) and that the enhanced bit is set. that means that the duty cycle obtained (51.95%) will be the inte rmediate value between duty cycles that can be obtained by 0x42 and 0x43 compare values (51.56%, 52.34%). 15.7 synchronous update to avoid unasynchronous and incoherent values in a cycle, if a synchronous update of one of several values is necess ary, all values can be updated at the same time at the end of the pwm cycle by the timer controller. the new set of val ues is calculated by software and the effective update can be initiated by software. figure 15-11. lock feature and synchronous update in normal operation, each write to a compare register is effective at the end of the current cycle. but some cases require that two or more compare registers are updated synchronously, and that may not be always possible, mostly at high speed pwm frequencies. that may result in some pwm periods with incoherent values. when using the lock feature (tlock4=1), the values written to the compare registers are not effective and temporarily buffered. when releasing the tlock4 bit, the update is initiated and the new whole set of values will be loade d at the end of th e current pwm cycle. see section 15.12.5 ?tccr4e ? timer/counter4 control register e? on page 169 . 15.8 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (bits pwm4x and wgm40) and compare output mode (com4x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generati on mode bits do. the com4x1:0 bits control whether the pwm output generated should be inverted, non-inverted or complementary. for non-pwm modes the com4x1:0 bits control whether the output should be set, cleared, or tog- gled at a compare match. 15.8.1 normal mode the simplest mode of operation is the normal mode (pwm4x = 0), the counter counts from bottom to top (defined as ocr4c) then restarts from bottom. the ocr4c defines the top value for the counter, hence also its resolution, and allows control of the compare match output frequency. in toggle compare output mode the waveform output (ocw4x) is toggled at compare match between tcnt4 and ocr4x. in non-inverting compare output mode the regulation loop calculation writing to timer registers set j request for an update cycle with set i cycle with set i cycle with set i cycle with set i cycle with set j tlock4=1 tlock4=0
150 7766f?avr?11/10 atmega16/32u4 waveform output is cleared on the compare match. in inverting compare output mode the waveform output is set on compare match. the timing diagram for the normal mode is shown in figure 15-12 . the counter value (tcnt4) that is shown as a histogram in the timing diagram is incremented until the counter value matches the top value. the counter is then cleared at the following clock cycle the diagram includes the waveform output (ocw4x) in toggle compare mode. the small horizontal line marks on the tcnt4 slopes represent compare matches between ocr4x and tcnt4. figure 15-12. normal mode, timing diagram the timer/counter overflow flag (tov4) is se t in the same clock cycle as the tcnt4 becomes zero. the tov4 flag in this case behaves like a 11t h bit, except that it is only set, not cleared. however, combined with the timer overflow inte rrupt, that automatically clears the tov4 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. for generating a waveform, the ocw4x output can be set to toggle its logical level on each compare match by setting the compare output mode bits to tog- gle mode (com4x1:0 = 1). the oc4x value will not be visible on the port pin unless the data direction for the pin is set to output. the wa veform generated will have a maximum frequency of f oc4x = f clkt4 /4 when ocr4c is set to zero. the waveform frequency is defined by the following equation: resolution shows how many bit is required to express the value in the ocr4c register. it is cal- culated by following equation: resolution pwm = log 2 (ocr4c + 1). tcntn ocwnx (comnx=1) ocnx interrupt flag set 1 4 period 2 3 tovn interrupt flag set f oc 4 x f clkt4 21 ocr 4 c + () ? ------------------------------------------ - =
151 7766f?avr?11/10 atmega16/32u4 the output compare pin configurations in normal mode are described in table 15-2 . 15.8.2 fast pwm mode the fast pulse width modulation or fast pwm mode (pwm4x = 1 and wgm40 = 0) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to top (defined as ocr4c) then restarts from bottom. in non-inverting compare output mode the waveform output (ocw4x) is cleared on the compare match between tcnt4 and ocr4x and set at bottom. in inverting compare output mode, the waveform output is set on compare match and cleared at bottom. in complementary compare output mode the waveform output is cleared on the compare match and set at bottom. due to the single-slope operation, the operatin g frequency of the fast pwm mode can be twice as high as the phase and frequency correct pwm mode that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physicall y small sized external components (coils, capacitors), and therefore reduces total system cost. the timing diagram for the fast pwm mode is shown in figure 15-13 . the counter is incre- mented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the tcnt4 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes the waveform output in non- inverted and inverted compare output modes. the small horizontal line marks on the tcnt4 slopes represent compare matches between ocr4x and tcnt4. figure 15-13. fast pwm mode, timing diagram table 15-2. output compare pin configurations in normal mode com4x1 com4x0 oc4x pin oc4x pin 0 0 disconnected disconnected 0 1 disconnected oc4x 1 0 disconnected oc4x 1 1 disconnected oc4x tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocwnx ocwnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7
152 7766f?avr?11/10 atmega16/32u4 the timer/counter overflow flag (tov4) is set each time the counter reaches top. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value.4in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc4x pins. set- ting the com4x1:0 bits to two will produce a non-inverted pwm and setting the com4x1:0 to three will produce an inverted pwm output. setting the com4x1:0 bits to one will enable com- plementary compare output mode and produce both the non-inverted (oc4x) and inverted output (oc4x ). the actual value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the waveform output (ocw4x) at the compare match between ocr4x and tcnt4, and clearing (or setting) the waveform output at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the number of steps in single-slope operation. the value of n equals either to the top value. the extreme values for the ocr4c register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr4c is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr4c equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com4x1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting the waveform output (ocw4x) to toggle its logical level on each compare match (com4x1:0 = 1). the waveform generate d will have a maximum frequency of f oc4 = f clkt4 /4 when ocr4c is set to three. the general i/o port function is overridden by the output compare value (oc4x / oc4x ) from the dead time generator, if either of the com4x1:0 bits are set and the data direction register bits for the oc4x and oc4x pins are set as an output. if the com4x1:0 bits are cleared, the actual value from the port regist er will be visible on the port pin. the output compare pin config- urations are described in table 15-3 . 15.8.3 phase and frequency correct pwm mode the phase and frequency correct pwm mode (pwm4x = 1 and wgm40 = 1) provides a high resolution phase and frequency correct pwm waveform generation option. the phase and frequency correct pwm mode is based on a dual-slope operation. the counter counts repeat- edly from bottom to top (defined as ocr4c) and then from top to bottom. in non- inverting compare output mode the waveform output (ocw4x) is cleared on the compare table 15-3. output compare pin configurations in fast pwm mode com4x1 com4x0 oc4x pin oc4x pin 0 0 disconnected disconnected 01oc4x oc4x 1 0 disconnected oc4x 1 1 disconnected oc4x f ocnxpwm f clkt4 n ------------ - =
153 7766f?avr?11/10 atmega16/32u4 match between tcnt4 and ocr4x while upcounting, and set on the compare match while down-counting. in inverting output compare mode, the operation is inverted. in complementary compare output mode, the waveform output is cleared on the compare match and set at bot- tom. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feat ure of the dual-slope pwm modes, these modes are preferred for motor control applications. the timing diagram for the phase and frequency correct pwm mode is shown on figure 15-14 in which the tcnt4 value is shown as a histogra m for illustrating the dua l-slope operation. the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direction. the tcnt4 value w ill be equal to top for one timer clock cycle. the diagram includes the waveform output (ocw4x) in non-inverted and inverted compare output mode. the small horizontal line marks on the tcnt4 slopes represent compare matches between ocr4x and tcnt4. figure 15-14. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tov4) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in the phase and frequency correct pwm mode, the compare unit allows generation of pwm waveforms on the oc4x pins. setting the com4 x1:0 bits to two will produce a non-inverted pwm and setting the com4 x1:0 to three will produce an in verted pwm output. setting the com4a1:0 bits to one will enable complementary compare ou tput mode and produce both the non-inverted (oc4x) and inverted output (oc4x ). the actual values will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the waveform output (ocw4x) at the compare match between ocr4x and tcnt4 when the counter increments, and setting (or clearing) the waveform output at compare match when the counter decrements. the pwm fr equency for the output when using the phase and frequency correct pwm can be calculated by the following equation: tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocwnx ocwnx (comnx = 2) (comnx = 3) ocrnx update f ocnxpcpwm f clkt4 n ------------ - =
154 7766f?avr?11/10 atmega16/32u4 the n variable represents the number of steps in dual-slope operation. the value of n equals to the top value. the extreme values for the ocr4c register represent special cases when generating a pwm waveform output in the phase and frequency correct pwm mode. if the ocr4c is set equal to bottom, the output will be continu ously low and if set equal to max the output will be continu- ously high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. the general i/o port function is overridden by the output compare value (oc4x / oc4x ) from the dead time generator, if either of the com4x1:0 bits are set and the data direction register bits for the oc4x and oc4x pins are set as an output. if the com4x1:0 bits are cleared, the actual value from the port register will be visible on the port pin. the conf igurations of the output compare pins are described in table 15-4 . 15.8.4 pwm6 mode the pwm6 mode (pwm4a = 1, wgm41 = 1 and wgm40 = x) provide pwm waveform genera- tion option e.g. for controlling brushless dc (bldc) motors. in the pwm6 mode the ocr4a register controls all six output compare waveforms as the same waveform output (ocw4a) from the waveform generator is used for generating all waveforms. the pwm6 mode also pro- vides an output compare override enable regi ster (oc4oe) that can be used with an instant response for disabling or enabling the output compare pins. if the output compare override enable bit is cleared, the actual value from the port register will be visible on the port pin. the pwm6 mode provides two counter operation modes, a single-slope operation and a dual- slope operation. if the single-slope operation is selected (the wgm40 bit is set to 0), the counter counts from bottom to top (defined as ocr4c) then restart from bottom like in fast pwm mode. the pwm waveform is generated by setting (or clearing) the waveform output (ocw4a) at the compare match between ocr4a and tcnt4, and clearing (or setting) the waveform output at the timer clock cycle the counter is cleared (changes from top to bottom). the timer/counter overflow flag (tov4) is set each time the counter reaches the top and, if the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. whereas, if the dual-slope operation is selected (the wgm40 bit is set to 1), the counter counts repeatedly from bottom to top (defined as ocr4c) and then from top to bottom like in phase and frequency correct pwm mode. the pwm waveform is generated by setting (or clearing) the waveform output (ocw4a) at the compare match between ocr4a and tcnt4 when the counter increments, and clearing (or setting) the waveform output at the he compare match between ocr4a and tcnt4 when the coun ter decrements. the timer/counter overflow flag (tov4) is set each time the counter reaches the bottom and, if the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. the timing diagram for the pwm6 mode in single-slope operation (wgm41 = 0) when the com4a1:0 bits are set to ?10? is shown in figure 15-15 . the counter is incremented until the table 15-4. output compare pin configurations in phase and frequency correct pwm mode com4x1 com4x0 oc4x pin oc4x pin 0 0 disconnected disconnected 01oc4x oc4x 1 0 disconnected oc4x 1 1 disconnected oc4x
155 7766f?avr?11/10 atmega16/32u4 counter value matches the top value. the counter is then cleared at the following timer clock cycle. the tcnt4 value is in the timing diagram shown as a histogram for illustrating the single- slope operation. the timing diagram includes output compare pins oc4a and oc4a, and the corresponding output compare override enable bits (oc4oe1..oc4oe0). figure 15-15. pwm6 mode, single-slope operation, timing diagram the general i/o port function is overridden by the output compare value (oc4x / oc4x ) from the dead time generator if either of the com4x1:0 bits are set. the output compare pins can also be overridden by the output compare override enable bits oc4oe5..oc4oe0. if an over- ride enable bit is cleared, the actual value from the port register will be visible on the port pin and, if the override enable bit is set, the output compare pin is allowed to be connected on the port pin. the output compare pin configurations are described in table 15-5 . table 15-5. output compare pin configurations in pwm6 mode com4a1 com4a0 oc4a pin (pc6) oc4a pin (pc7) 0 0 disconnected disconnected 01oc4a ? oc4oe0 oc4a ? oc4oe1 10oc4a ? oc4oe0 oc4a ? oc4oe1 11oc4a ? oc4oe0 oc4a ? oc4oe1 com4b1 com4b0 oc4b pin (pb5) oc4b pin (pb6) 0 0 disconnected disconnected 01oc4a ? oc4oe2 oc4a ? oc4oe3 tcnt4 oc4a pin oc4a pin oc4b pin oc4b pin oc4d pin oc4d pin oc4oe0 oc4oe1 oc4oe2 oc4oe3 oc4oe4 oc4oe5 ocw4a
156 7766f?avr?11/10 atmega16/32u4 15.9 timer/counter timing diagrams the timer/counter is a synchron ous design and the timer clock (clk t4 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 15-16 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase and frequency correct pwm mode. figure 15-17 shows the same timing data, but with the prescaler enabled, in all modes other than phase and frequency correct pwm mode. figure 15-18 shows the setting of ocf4a, ocf4b and ocf4d in all modes, and figure 15-19 shows the setting of tov4 in phase and frequency correct pwm mode. figure 15-16. timer/counter timing diagram, no prescaling figure 15-17. timer/counter timing dia gram, with prescaler (f clkt4 /8) 10oc4a ? oc4oe2 oc4a ? oc4oe3 11oc4a ? oc4oe2 oc4a ? oc4oe3 com4d1 com4d0 oc4d pin (pd6) oc4d pin (pd7) 0 0 disconnected disconnected 01oc4a ? oc4oe4 oc4a ? oc4oe5 10oc4a ? oc4oe4 oc4a ? oc4oe5 11oc4a ? oc4oe4 oc4a ? oc4oe5 table 15-5. output compare pin configurations in pwm6 mode (continued) com4a1 com4a0 oc4a pin (pc6) oc4a pin (pc7) clk tn (clk pck /1) tovn clk pck tcntn top - 1 top bottom bottom + 1 tovn tcntn top - 1 top bottom bottom + 1 clk pck clk tn (clk pck /8)
157 7766f?avr?11/10 atmega16/32u4 figure 15-18. timer/counter timing diagram, setting of ocf1x, with prescaler (f clkt4 /8) figure 15-19. timer/counter timing dia gram, with prescaler (f clkt4 /8) 15.10 fault protection unit the timer/counter4 incorporates a fault protection unit that can disable the pwm output pins, if an external event is triggered. the external signal indicating an event can be applied via the external interrupt int0 pin or alternatively, via the analog-comparator unit. the fault protection unit is illustrated by th e block diagram shown in figure 15-20 . the elements of the block diagram that are not directly a part of the fault protection unit are gray shaded. figure 15-20. fault protection unit block diagram when the fault protection mode is enabled by the fault protection enable (fpen4) bit and a change of the logic level (an event) occurs on the external interrupt pin (int0), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge detec- tor, a fault protection mode will be triggered. when a fault protection is triggered, the com4x bits are cleared, output comparators are disconnected from the pwm output pins and the portb register bits are connected on the pwm output pins. the fault protection enable (fpen4) is automatically cleared at the same system clock as the com4nx bits are cleared. if the fault protection interrupt enable bit (fpie4) is set, a fault protection interrupt is generated and the fpen4 bit is cleared. alternatively the fpen4 bit can be polled by software to figure out when the timer/counter has entered to fault protection mode. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk pck clk tn (clk pck /8) tovn tcntn bottom + 1 bottom + 1 bottom bottom + 1 clk pck clk tn (clk pck /8) analog comparator noise canceler int0 edge detector fpac4 fpnc4 fpes4 aco* fpen4 timer/counter4 fault_protection (int. req.)
158 7766f?avr?11/10 atmega16/32u4 15.10.1 fault protection trigger source the main trigger source for the fault protection unit is the external interrupt pin (int0). alterna- tively the analog comparator output can be used as trigger source for the fault protection unit. the analog comparator is selected as trigger source by setting the fault protection analog comparator (fpac4) bit in the timer/counter4 control register (tccr4d). be aware that changing trigger source can trigger a fault protection mode. therefore it is recommended to clear the fpf4 flag after changing trigger sour ce, setting edge detector or enabling the fault protection. both the external interrupt pin (int0) and the analog comparator output (aco) inputs are sam- pled using the same technique as for the t0 pin ( figure 12-1 on page 89 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increase s the delay by four system cloc k cycles. an input capture can also be triggered by software by controlling the port of the int0 pin. 15.10.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the fault protection noise canceler (fpnc4) bit in timer/counter4 control register d (tccr4d ). when enabled the noise canceler introduces additional four system cloc k cycles of delay from a change applied to the input. the noise can- celer uses the system clock and is therefore not affected by the prescaler.
159 7766f?avr?11/10 atmega16/32u4 15.11 accessing 10-bit registers if 10-bit values are written to the tcntn and ocrna/b/c/d registers, the 10-bit registers can be byte accessed by the avr cpu via the 8-bit da ta bus using two read or write operations. the 10-bit registers have a common 2-bit timer/counter4 high byte register (tc4h) that is used for temporary storing of the two msbs of the 10-bi t access. the same tc4h register is shared between all 10-bit registers. accessing the low byte triggers the 10-bit read or write operation. when the low byte of a 10-bit register is written by the cpu, the high byte stored in the tc4h register, and the low byte written are both copied into the 10-bit register in the same clock cycle. when the low byte of a 10-bit register is read by the cpu, the high byte of the 10-bit register is copied into the tc4h register in the same clock cycle as the low byte is read. to do a 10-bit write, the high byte must be written to the tc4h register before the low byte is written. for a 10-bit read, the low byte must be read before the high byte. the following code examples show how to access the 10-bit timer registers assuming that no interrupts updates the tc4h register. the same pr inciple can be used directly for accessing the ocrna/b/c/c/d registers. note: 1. the example code assumes that the part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructi ons that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbr s?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example returns the tcntn value in the r17:r16 register pair. assembly code example ... ; set tcnt n to 0x01ff ldi r17,0x01 ldi r16,0xff out tc n h,r17 out tcnt n ,r16 ; read tcnt n into r17:r16 in r16,tcnt n in r17,tc n h ... c code example unsigned int i; ... /* set tcntn to 0x01ff */ tcnh = 0x01; tcntn = 0xff; /* read tcntn into i */ i = tcntn; i |= (( unsigned int )tcnh << 8); ...
160 7766f?avr?11/10 atmega16/32u4 it is important to notice that accessing 10-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 10-bit register, and the interrupt code updates the tc4h register by accessing the same or any other of the 10-bit timer registers, then the result of the access outside the interrupt will be corrupted. therefore, when both the main code and the interrupt code update the tc4h regi ster, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcntn register contents. reading any of the ocrna/b/c/d registers can be done by using the same principle. note: 1. the example code assumes that the part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructi ons that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbr s?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example returns the tcntn value in the r17:r16 register pair. assembly code example tim1_readtcnt n : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt n into r17:r16 in r16,tcnt n in r17,tc n h ; restore global interrupt flag out sreg,r18 ret c code example unsigned int tim1_readtcntn( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* read tcntn into i */ i = tcntn; i |= ((unsigned int)tcnh << 8); /* restore global interrupt flag sreg = sreg; return i; }
161 7766f?avr?11/10 atmega16/32u4 the following code examples show how to do an atomic write of the tcntn register contents. writing any of the ocrna/b/c/d registers can be done by using the same principle. note: 1. the example code assumes that the part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructi ons that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbr s?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example requires that the r17:r16 register pair contains the value to be writ- ten to tcntn. 15.11.1 reusing the temporary high byte register if writing to more than one 10-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. assembly code example tim1_writetcnt n : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt n to r17:r16 out tc n h,r17 out tcnt n ,r16 ; restore global interrupt flag out sreg,r18 ret c code example void tim1_writetcntn( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* set tcntn to i */ tcnh = (i >> 8); tcntn = (unsigned char)i; /* restore global interrupt flag */ sreg = sreg; }
162 7766f?avr?11/10 atmega16/32u4 15.12 register description 15.12.1 tccr4a ? timer/counter4 control register a ? bits 7,6 - com4a1, com4a0: comparator a output mode, bits 1 and 0 these bits control the behavior of the wave form output (ocw4a) and the connection of the output compare pin (oc4a). if one or both of the com4a1:0 bits are set, the oc4a output overrides the normal port functionality of the i/o pin it is connected to. the complementary oc4b output is connected only in pwm modes when the com4a1:0 bits are set to ?01?. note that the data direction register (d dr) bit corresponding to the oc4a and oc4a pins must be set in order to enable the output driver. the function of the com4a1:0 bits depends on the pwm4a, wgm40 and wgm41 bit settings. table 15-6 shows the com4a1:0 bit functionality when the pwm4a bit is set to normal mode (non-pwm). table 15-7 shows the com4a1:0 bit functionality when the pwm4a, wgm40 and wgm41 bits are set to fast pwm mode. bit 76543210 com4a1 com4a0 com4b1 com4b0 foc4a foc4b pwm4a pwm4b tccr4a read/write r/w r/w r/w r/w w w r/w r/w initial value00000000 table 15-6. compare output mode, normal mode (non-pwm) com4a1..0 ocw4a behavior oc4a pin oc4a pin 00 normal port operation. disconnected disconnected 01 toggle on compare match. connected disconnected 10 clear on compare match. connected disconnected 11 set on compare match. connected disconnected table 15-7. compare output mode, fast pwm mode com4a1..0 ocw4a behavior oc4a oc4a 00 normal port operation. disconnected disconnected 01 cleared on compare match. set when tcnt4 = 0x000. connected connected 10 cleared on compare match. set when tcnt4 = 0x000. connected disconnected 11 set on compare match. cleared when tcnt4 = 0x000. connected disconnected
163 7766f?avr?11/10 atmega16/32u4 table 15-8 shows the com4a1:0 bit functionality when the pwm4a, wgm40 and wgm41 bits are set to phase and frequency correct pwm mode. table 15-9 shows the com4a1:0 bit functionality when the pwm4a, wgm40 and wgm41 bits are set to single-slope pwm6 mode. in the pwm6 mode the same waveform output (ocw4a) is used for generating all waveforms and the output compare values oc4a and oc4a are con- nected on oc4x and oc4x pins as described below. table 15-10 shows the com4a1:0 bit functionality when the pwm4a, wgm40 and wgm41 bits are set to dual-slope pwm6 mode.i ? bits 5,4 - com4b1, com4b0: comparator b output mode, bits 1 and 0 these bits control the behavior of the wave form output (ocw4b) and the connection of the output compare pin (oc4b). if one or both of the com4b1:0 bits are set, the oc4b output overrides the normal port functionality of the i/o pin it is connected to. the complementary oc4b output is connected only in pwm modes when the com4b1:0 bits are set to ?01?. note table 15-8. compare output mode, phase and frequency correct pwm mode com1a1..0 ocw1a behavior oc4a pin oc4a pin 00 normal port operation. disconnected disconnected 01 cleared on compare match when up-counting. set on compare match when down-counting. connected connected 10 cleared on compare match when up-counting. set on compare match when down-counting. connected disconnected 11 set on compare match when up-counting. cleared on compare match when down-counting. connected disconnected table 15-9. compare output mode, single-slope pwm6 mode com4a1..0 ocw4a behavior oc4x pin oc4x pin 00 normal port operation. disconnected disconnected 01 cleared on compare match. set when tcnt4 = 0x000. oc4a oc4a 10 cleared on compare match. set when tcnt4 = 0x000. oc4a oc4a 11 set on compare match. cleared when tcnt4 = 0x000. oc4a oc4a table 15-10. compare output mode, dual-slope pwm6 mode com4a1..0 ocw4a behavior oc4x pin oc4x pin 00 normal port operation. disconnected disconnected 01 cleared on compare match when up-counting. set on compare match when down-counting. oc4a oc4a 10 cleared on compare match when up-counting. set on compare match when down-counting. oc4a oc4a 11 set on compare match when up-counting. cleared on compare match when down-counting. oc4a oc4a
164 7766f?avr?11/10 atmega16/32u4 that the data direction register (ddr) bit corresponding to the oc 4b pin must be set in order to enable the output driver. the function of the com4b1:0 bits depends on the pwm4b and wgm40 bit settings. table 15- 11 shows the com4b1:0 bit functionality when the pwm4b bit is set to normal mode (non- pwm). table 15-12 shows the com4b1:0 bit functionality when the pwm4b and wgm40 bits are set to fast pwm mode. table 15-13 shows the com4b1:0 bit functionality when the pwm4b and wgm40 bits are set to phase and frequency correct pwm mode. ? bit 3 - foc4a: force output compare match 4a the foc4a bit is only active when the pwm4a bit specify a non-pwm mode. writing a logical one to this bit forces a change in the waveform output (ocw4a) and the out- put compare pin (oc4a) according to the values already set in com4a1 and com4a0. if com4a1 and com4a0 written in the same cycle as foc4a, the new settings will be used. the force output compare bit can be used to change the output pin value regardless of the timer table 15-11. compare output mode, normal mode (non-pwm) com4b1..0 ocw4b behavior oc4b pin oc4b pin 00 normal port operation. disconnected disconnected 01 toggle on compare match. connected disconnected 10 clear on compare match. connected disconnected 11 set on compare match. connected disconnected table 15-12. compare output mode, fast pwm mode com4b1..0 ocw4b behavior oc4b pin oc4b pin 00 normal port operation. disconnected disconnected 01 cleared on compare match. set when tcnt4 = 0x000. connected connected 10 cleared on compare match. set when tcnt4 = 0x000. connected disconnected 11 set on compare match. cleared when tcnt4 = 0x000. connected disconnected table 15-13. compare output mode, phase and frequency correct pwm mode com4b1..0 ocw4b behavior oc4b pin oc4b pin 00 normal port operation. disconnected disconnected 01 cleared on compare match when up-counting. set on compare match when down-counting. connected connected 10 cleared on compare match when up-counting. set on compare match when down-counting. connected disconnected 11 set on compare match when up-counting. cleared on compare match when down-counting. connected disconnected
165 7766f?avr?11/10 atmega16/32u4 value. the automatic action programmed in com4a1 and com4a0 takes place as if a compare match had occurred, but no interrupt is generated. the foc4a bit is always read as zero. ? bit 2 - foc4b: force output compare match 4b the foc4b bit is only active when the pwm4b bit specify a non-pwm mode. writing a logical one to this bit forces a change in the waveform output (ocw4b) and the out- put compare pin (oc4b) according to the values already set in com4b1 and com4b0. if com4b1 and com4b0 written in the same cycle as foc4b, the new settings will be used. the force output compare bit can be used to change the output pin value regardless of the timer value. the automatic action programmed in com4b1 and com4b0 takes place as if a compare match had occurred, but no interrupt is generated. the foc4b bit is always read as zero. ? bit 1 - pwm4a: pulse width modulator a enable when set (one) this bit enables pwm mode based on comparator ocr4a ? bit 0 - pwm4b: pulse width modulator b enable when set (one) this bit enables pwm mode based on comparator ocr4b. 15.12.2 tccr4b ? timer/counter4 control register b ? bit 7 - pwm4x: pwm inversion mode when this bit is set (one), the pwm inversion mode is selected and the dead time generator outputs, oc4x and oc4x are inverted. ? bit 6 - psr4: prescaler reset timer/counter4 when this bit is set (one), the timer/counter4 pr escaler (tcnt4 is unaffe cted) will be reset. the bit will be cleared by hard ware after the operation is performed. writing a zero to this bit will have no effect. this bit will always read as zero. ? bits 5,4 - dtps41, dtps40: dead time prescaler bits the timer/counter4 control register b is a 8-bit read/write register. the dedicated dead time prescaler in front of the dead time generator can divide the timer/counter4 clock (pck or ck) by 1, 2, 4 or 8 providing a large range of dead times that can be generated. the dead time prescaler is controlled by two bits dtps41 and dtps40 from the dead time prescaler register. these bits define the division factor of the dead time prescaler. the division factors are given in table 15-14 . bit 76543210 pwm4x psr4 dtps41 dtps40 cs43 cs42 cs41 cs40 tccr4b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
166 7766f?avr?11/10 atmega16/32u4 ? bits 3 .. 0 - cs43, cs42, cs41, cs40: clock select bits 3, 2, 1, and 0 the clock select bits 3, 2, 1, and 0 define the prescaling source of timer/counter4. the stop condition provides a timer enable/disable function. 15.12.3 tccr4c ? timer/counter4 control register c ? bits 7,6 - com4a1s, com4 a0s: comparator a output mode, bits 1 and 0 these bits are the shadow bits of the com4a1 and com4a0 bits that are described in the sec- tion ?tccr4a ? timer/counter4 control register a? on page 162 . table 15-14. division factors of the dead time prescaler dtps41 dtps40 prescaler divi des the t/c4 clock by 0 0 1x (no division) 012x 104x 118x table 15-15. timer/counter4 prescaler select cs43 cs42 cs41 cs40 asynchronous clocki ng mode synchronous clocking mode 0000t/c4 stopped t/c4 stopped 0001pck ck 0010pck/2 ck/2 0011pck/4 ck/4 0100pck/8 ck/8 0101pck/16 ck/16 0110pck/32 ck/32 0111pck/64 ck/64 1000pck/128 ck/128 1001pck/256 ck/256 1010pck/512 ck/512 1011pck/1024 ck/1024 1100pck/2048 ck/2048 1101pck/4096 ck/4096 1110pck/8192 ck/8192 1111pck/16384 ck/16384 bit 76543210 com4a1s com4a0s com4b1s comab0s com4d1 com4d0 foc4d pwm4d tccr4c read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000
167 7766f?avr?11/10 atmega16/32u4 ? bits 5,4 - com4b1s, com4 b0s: comparator b output mode, bits 1 and 0 these bits are the shadow bits of the com4a1 and com4a0 bits that are described in the sec- tion ?tccr4a ? timer/counter4 control register a? on page 162 . ? bits 3,2 - com4d1, com4d0: comparator d output mode, bits 1 and 0 these bits control the behavior of the waveform output (ocw4d) and the connection of the output compare pin (oc4d). if one or both of the com4d1:0 bits are set, the oc4d output overrides the normal port functionality of the i/o pin it is connected to. the complementary oc4d output is connected only in pwm modes when the com4d1:0 bits are set to ?01?. note that the data direction register (ddr) bit corres ponding to the oc4d pin must be set in order to enable the output driver. the function of the com4d1:0 bits depends on the pwm4d and wgm40 bit settings. table 15- 16 shows the com4d1:0 bit functionality when t he pwm4d bit is set to a normal mode (non- pwm). table 15-17 shows the com4d1:0 bit functionality when the pwm4d and wgm40 bits are set to fast pwm mode. table 15-18 on page 168 shows the com4d1:0 bit functionality when the pwm4d and wgm40 bits are set to phase and frequency correct pwm mode. table 15-16. compare output mode, normal mode (non-pwm) com4d1..0 ocw4d behavior oc4d pin oc4d pin 00 normal port operation. disconnected disconnected 01 toggle on compare match. connected disconnected 10 clear on compare match. connected disconnected 11 set on compare match. connected disconnected table 15-17. compare output mode, fast pwm mode com4d1..0 ocw4d behavior oc4d pin oc4d pin 00 normal port operation. disconnected disconnected 01 cleared on compare match. set when tcnt4 = 0x000. connected connected 10 cleared on compare match. set when tcnt4 = 0x000. connected disconnected 11 set on compare match. clear when tcnt4 = 0x000. connected disconnected
168 7766f?avr?11/10 atmega16/32u4 ? bit 1 - foc4d: force output compare match 4d the foc4d bit is only active when the pwm4d bit specify a non-pwm mode. writing a logical one to this bit forces a change in the waveform output (ocw4d) and the out- put compare pin (oc4d) according to the values already set in com4d1 and com4d0. if com4d1 and com4d0 written in the same cycle as foc4d, th e new settings will be used. the force output compare bit can be used to change the output pin value regardless of the timer value. the automatic action programmed in com4d1 and com4d0 takes place as if a compare match had occurred, but no interrupt is generated. the foc4d bit is always read as zero. ? bit 0 - pwm4d: pulse width modulator d enable when set (one) this bit enables pwm mode based on comparator ocr4d. 15.12.4 tccr4d ? timer/counter4 control register d ? bit 7 - fpie4: fault protection interrupt enable setting this bit (to one) enables the fault protection interrupt. ? bit 6? fpen4: fault protection mode enable setting this bit (to one) activates the fault protection mode. ? bit 5 ? fpnc4: fault protection noise canceler setting this bit activates the fault protection no ise canceler. when the noi se canceler is acti- vated, the input from the fault protection pin (int0) is filtered. the filter function requires four successive equal valued samples of the int0 pin for changing its output. the fault protection is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 4 ? fpes4: fault protection edge select this bit selects which edge on the fault protecti on pin (int0) is used to trigger a fault event. when the fpes4 bit is written to zero, a falling (negative) edge is used as trigger, and when the fpes4 bit is written to one, a rising (positive) edge will trigger the fault. table 15-18. compare output mode, phase and frequency correct pwm mode com4d1..0 ocw4d behavior oc4d pin oc4d pin 00 normal port operation. disconnected disconnected 01 cleared on compare match when up-counting. set on compare match when down-counting. connected connected 10 cleared on compare match when up-counting. set on compare match when down-counting. connected disconnected 11 set on compare match when up-counting. cleared on compare match when down-counting. connected disconnected bit 76543210 fpie4 fpen4 fpnc4 fpes4 fpac4 fpf4 wgm41 wgm40 tccr4d read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000
169 7766f?avr?11/10 atmega16/32u4 ? bit 3 - fpac4: fault protection analog comparator enable when written logic one, this bit enables the fault protection function in timer/counter4 to be triggered by the analog comparator. the comparator output is in this case directly connected to the fault protection front-end logic, making the comparator utilize the noise canceler and edge select features of the timer/counter4 fault protection interrupt. when written logic zero, no con- nection between the analog comparator and the fault protection function exists. to make the comparator trigger the timer/counter4 fault protection interrupt, the fpie4 bit in the timer/counter4 control regist er d (tccr4d) must be set. ? bit 2- fpf4: fault protection interrupt flag when the fpie4 bit is set (one), the fault protec tion interrupt is enabled. activity on the pin will cause an interrupt request even, if the fault protec tion pin is configured as an output. the corre- sponding interrupt of fault protection interrupt request is executed from the fault protection interrupt vector. the bit fpf4 is cleared by hardware when executing the corresponding inter- rupt handling vector. alternatively, fpf4 is clea red after a synchronization clock cycle by writing a logical one to the flag. when the sreg i-bit, fpie4 and fpf4 are set, the fault interrupt is executed. ? bits 1:0 - wgm41, wgm40: waveform generation mode bits this bit associated with the pwm4x bits c ontrol the counting sequence of the counter, the source for type of waveform generation to be used, see table 15-19 . modes of operation sup- ported by the timer/counter4 are: normal mode (counter), fast pwm mode, phase and frequency correct pwm and pwm6 modes. 15.12.5 tccr4e ? timer/counter4 control register e ? bit 7 - tlock4: register update lock this bit controls the compare registers update. when this bit is set, writing to the compare reg- isters will not affect the output, however the values are stored and will be updated to the compare registers when the tlock4 bit will be cleared. refer to section 15.7 ?synchronous update? on page 149 for more details. table 15-19. waveform generation mode bit description pwm4x wgm41..40 timer/counter mode of operation top update of ocr4x at tov4 flag set on 0 xx normal ocr4c immediate top 1 00 fast pwm ocr4c top top 1 01 phase and frequency correct pwm ocr4c bottom bottom 1 10 pwm6 / single-slope ocr4c top top 1 11 pwm6 / dual-slope ocr4c bottom bottom bit 76543210 tlock4 enhc4 oc4oe5 oc4oe4 oc4oe3 oc4oe2 oc4oe1 oc4oe0 tccr4e read/write r r r/w r/w r/w r/w r/w r/w initial value 00000000
170 7766f?avr?11/10 atmega16/32u4 ? bit 6- enhc4: enhanced compare/pwm mode when this bit is set, the waveform generation module works in enhanced mode: the compare registers ocr4a/b/d can welcome one more accura cy bit, while the lsb determines on which clock edge the compare condition is signalled and the output pin level is updated. ? bits 5:0 ? oc4oe5:oc4oe0: output compare override enable bits these bits are the output compare override enable bits that are used to connect or disconnect the output compare pins in pwm6 modes with an instant response on the corresponding out- put compare pins. the actual value from the port register will be visi ble on the port pin, when the output compare override enable bit is cleared. table 15-20 shows the output compare override enable bits and their co rresponding output compare pins. 15.12.6 tcnt4 ? timer/counter4 this 8-bit register contains the value of timer/counter4. the timer/counter4 is realized as a 10-bit up/ down counter with read and write access. due to synchronization of the cpu, timer/counter4 data written into timer/counter4 is delayed by one and half cpu clock cycles in syn chronous mode and at most o ne cpu clock cycles for asyn- chronous mode. when a 10-bit accuracy is preferred, special procedures must be followed for accessing the 10-bit tcnt4 register via t he 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . alternatively the timer/counter4 can be used as an 8-bit timer/counter. note that the timer/counter4 always starts counting up after writing the tcnt4 register. 15.12.7 tc4h ? timer/counter4 high byte the temporary timer/counter4 register is an 2-bit read/write register. ? bits 7:3- res: reserved bits these bits are reserved bits in the atmega16u4/atmega32u4 and always reads as zero. ? bits 2- tc410: additional msb bits for 11-bit accesses in enhanced pwm mode if 10-bit accuracy is used, the timer/counter4 high byte register (tc4h) is used for temporary storing the msb bits (tc49, tc48) of the 10-bi t accesses. the same tc4h register is shared between all 10-bit registers within the timer/counter4. note that special procedures must be fol- lowed when accessing the 10-bit tcnt4 register via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . table 15-20. output compare override enable bits vs. output compare pins oc4oe0 oc4oe1 oc4oe2 oc4oe3 oc4oe4 oc4oe5 oc4a (pc6) oc4a (pc7) oc4b (pb5) oc4b (pb6) oc4d (pd6) oc4d (pd7) bit 76543210 4 msb lsb tcnt4 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 -----tc410tc49tc48tc4h read/writerrrrrrr/wr/w initial value00000000
171 7766f?avr?11/10 atmega16/32u4 ? bits 1:0 - tc49, tc48: two msb bits of the 10-bit accesses if 10-bit accuracy is used, the timer/counter4 high byte register (tc4h) is used for temporary storing the msb bits (tc49, tc48) of the 10-bi t accesses. the same tc4h register is shared between all 10-bit registers within the timer/counter4. note that special procedures must be fol- lowed when accessing the 10-bit tcnt4 register via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . 15.12.8 ocr4a ? timer/counter4 output compare register a the output compare register a is an 8-bit read/write register. the timer/counter output compare register a contains data to be continuously compared with timer/counter4. actions on compare matches are specified in tccr4a. a compare match does only occur if timer/counter4 counts to the ocr4a value. a software write that sets tcnt4 and ocr4a to the same value does not generate a compare match. a compare match will set the compar e interrupt flag ocf4a after a synchronization delay follow- ing the compare event. note that, if 10-bit accuracy is used special pr ocedures must be followed when accessing the internal 10-bit output compare registers via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . 15.12.9 ocr4b ? timer/counter4 output compare register b the output compare register b is an 8-bit read/write register. the timer/counter output compare register b contains data to be continuously compared with timer/counter4. actions on compare matches are specified in tccr4. a compare match does only occur if timer/counter4 counts to the ocr4b value. a software write that sets tcnt4 and ocr4b to the same value does not generate a compare match. a compare match will set the compar e interrupt flag ocf4b after a synchronization delay follow- ing the compare event. note that, if 10-bit accuracy is used special pr ocedures must be followed when accessing the internal 10-bit output compare registers via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . 15.12.10 ocr4c ? timer/counter4 output compare register c bit 76543210 msb lsb ocr4a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb ocr4b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb ocr44c read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111111
172 7766f?avr?11/10 atmega16/32u4 the output compare register c is an 8-bit read/write register. the timer/counter output compare register c co ntains data to be continuously compared with timer/counter4, and a compare ma tch will clear tcnt4. this regist er has the same function in normal mode and pwm modes. note that, if a smaller value than three is written to the output compare register c, the value is automatically replaced by three as it is a mini mum value allowed to be written to this register. note that, if 10-bit accuracy is used special pr ocedures must be followed when accessing the internal 10-bit output compare registers via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . 15.12.11 ocr4d ? timer/counter4 output compare register d the output compare register d is an 8-bit read/write register. the timer/counter output compare register d co ntains data to be continuously compared with timer/counter4. actions on compare matches are specified in tccr4a. a compare match does only occur if timer/counter4 counts to the ocr4d value. a software write that sets tcnt4 and ocr4d to the same value does not generate a compare match. a compare match will set the compar e interrupt flag ocf4d after a synchronization delay follow- ing the compare event. note that, if 10-bit accuracy is used special pr ocedures must be followed when accessing the internal 10-bit output compare registers via the 8-bit avr data bus. these procedures are described in section ?accessing 10-bit registers? on page 159 . 15.12.12 timsk4 ? timer/count er4 interrupt mask register ? bit 7- ocie4d: timer/counter4 output compare interrupt enable when the ocie4d bit is set (one) and the i-bit in the status register is set (one), the timer/counter4 compare match d interrupt is enabled. the corresponding interrupt at vector $010 is executed if a compare match d occurs. the compare flag in timer/counter4 is set (one) in the timer/counter interrupt flag register. ? bit 6 - ocie4a: timer/counter4 output compare interrupt enable when the ocie4a bit is set (one) and the i-bit in the status register is set (one), the timer/counter4 compare match a interrupt is enabled. the corresponding interrupt at vector $003 is executed if a compare match a occurs. the compare flag in timer/counter4 is set (one) in the timer/counter interrupt flag register. bit 76543210 msb lsb ocr4d read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocie4d ocie4a ocie4b toie4 timsk4 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
173 7766f?avr?11/10 atmega16/32u4 ? bit 5 - ocie4b: timer/counter4 output compare interrupt enable when the ocie4b bit is set (one) and the i-bit in the status register is set (one), the timer/counter4 compare match b interrupt is enabled. the corresponding interrupt at vector $009 is executed if a compare match b occurs. the compare flag in timer/counter4 is set (one) in the timer/counter interrupt flag register. ? bit 2 - toie4: timer/counter4 overflow interrupt enable when the toie4 bit is set (one) and the i-bit in the status register is set (one), the timer/counter4 overflow interrupt is enabled. the corresponding interrupt (at vector $004) is executed if an overflow in timer/counter4 occurs . the overflow flag (timer4) is set (one) in the timer/counter interrupt flag register - tifr4. 15.12.13 tifr4 ? timer/counte r4 interrupt flag register ? bit 7- ocf4d: output compare flag 4d the ocf4d bit is set (one) when compare match occurs between timer/counter4 and the data value in ocr4d - output compare register 4d. ocf4d is cleared by hardware when executing the corresponding interrupt handling vector. alte rnatively, ocf4d is cleared, after synchroniza- tion clock cycle, by writing a logic one to the flag. when the i-bit in sreg, ocie4d, and ocf4d are set (one), the timer/counter4 d compare match interrupt is executed. ? bit 6 - ocf4a: output compare flag 4a the ocf4a bit is set (one) when compare match occurs between timer/counter4 and the data value in ocr4a - output compare register 4a. ocf4a is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf4a is cleared, after synchroniza- tion clock cycle, by writing a logic one to the flag. when the i-bit in sreg, ocie4a, and ocf4a are set (one), the timer/counter4 a compare match interrupt is executed. ? bit 5 - ocf4b: output compare flag 4b the ocf4b bit is set (one) when compare match occurs between timer/counter4 and the data value in ocr4b - output compare register 4b. ocf4b is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf4b is cleared, after synchroniza- tion clock cycle, by writing a logic one to the flag. when the i-bit in sreg, ocie4b, and ocf4b are set (one), the timer/counter4 b compare match interrupt is executed. ? bit 2 - tov4: timer/counter4 overflow flag in normal mode and fast pwm mode the tov4 bit is set (one) each time the counter reaches top at the same clock cycle when the counter is reset to bottom. in phase and frequency correct pwm mode the tov4 bit is set (one) each time the counter reaches bottom at the same clock cycle when zero is clocked to the counter. the bit tov4 is cleared by hardware when ex ecuting the corresponding interrupt handling vec- tor. alternatively, tov4 is cleared, after sync hronization clock cycle, by writing a logical one to the flag. when the sreg i-bit, and toie4 (tim er/counter4 overflow interrupt enable), and tov4 are set (one), the timer/counter4 overflow interrupt is executed. bit 76543210 ocf4d ocf4a ocf4b tov4 tifr4 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
174 7766f?avr?11/10 atmega16/32u4 15.12.14 dt4 ? timer/counter4 dead time value the dead time value register is an 8-bit read/write register. the dead time delay of all timer/counter4 channels are adjusted by the dead time value regis- ter, dt4. the register consists of two fields, dt4h3..0 and dt4l3..0, one for each complementary output. therefore a different dead time delay can be adjusted for the rising edge of oc4x and the rising edge of oc4x . ? bits 7:4- dt4h3:dt4h0: dead time value for oc4x output the dead time value for the oc1x output. the dead time delay is set as a number of the pres- caled timer/counter clocks. the minimum dead time is zero and the maximum dead time is the prescaled time/counter clock period multiplied by 15. ? bits 3:0- dt4l3:dt4l0: dead time value for oc4x output the dead time value for the oc4x output. the dead time delay is set as a number of the pres- caled timer/counter clocks. the minimum dead time is zero and the maximum dead time is the prescaled time/counter clock period multiplied by 15. bit 76543210 dt4h3 dt4h2 dt4h1 dt4h0 dt4l3 dt4l2 dt4l1 dt4l0 dt4 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000
175 7766f?avr?11/10 atmega16/32u4 16. output compare modulator (ocm1c0a) 16.1 overview the output compare modulator (ocm) allows generation of waveforms modulated with a carrier frequency. the modulator uses the outputs from the output compare unit c of the 16-bit timer/counter1 and the output compare unit of the 8-bit timer/counter0. for more details about these timer/counters see ?timer/counter0, timer/counter1, and timer/counter3 pres- calers? on page 89 . figure 16-1. output compare modulator, block diagram when the modulator is enabled, the two output compare channels are modulated together as shown in the block diagram ( figure 16-1 ). 16.2 description the output compare unit 1c and output compare unit 2 shares the pb7 port pin for output. the outputs of the output compare units (oc1c and oc0a) overrides the normal portb7 register when one of them is enabled (i.e., when comnx1:0 is not equal to zero). when both oc1c and oc0a are enabled at the same time, the modulator is automatically enabled. the functional equivalent schematic of the modulator is shown on figure 16-2 . the schematic includes part of the timer/counter units and the port b pin 7 output driver circuit. figure 16-2. output compare modulator, schematic oc1c pin oc1c / oc0a / pb7 timer/counter 1 timer/counter 0 oc0a portb7 ddrb7 dq dq pin coma01 coma00 databus oc1c / oc0a/ pb7 com1c1 com1c0 modulator 1 0 oc1c dq oc0a dq ( from waveform generator ) ( from waveform generator ) 0 1 vcc
176 7766f?avr?11/10 atmega16/32u4 when the modulator is enabled the type of modulation (logical and or or) can be selected by the portb7 register. note that the ddrb7 controls the direction of the port independent of the comnx1:0 bit setting. 16.2.1 timing example figure 16-3 illustrates the modulator in ac tion. in this example the ti mer/counter1 is set to oper- ate in fast pwm mode (non-inverted) and timer/counter0 uses ctc waveform mode with toggle compare output mode (comnx1:0 = 1). figure 16-3. output compare modulator, timing diagram in this example, timer/counter0 provides the carrier, while the modulating signal is generated by the output compare unit c of the timer/counter1. the resolution of the pwm signal (oc1c) is reduced by the modulation. the reduction factor is equal to the number of system clock cycles of one period of the carrier (oc0a). in this example the resolution is reduced by a factor of two. the reason for the reduction is illustrated in figure 16-3 at the second and third period of the pb7 output when portb7 equals zero. the period 2 high time is one cycle longer than the period 3 high time, but the result on the pb7 output is equal in both periods. 1 2 oc0a (ctc mode) oc1c (fpwm mode) pb7 (portb7 = 0) pb7 (portb7 = 1) (period) 3 clk i/o
177 7766f?avr?11/10 atmega16/32u4 17. serial peripheral interface ? spi the serial peripheral interface (spi) allows hi gh-speed synchronous data transfer between the atmega16u4/atmega32u4 and peripheral devices or between several avr devices. the atmega16u4/atmega32u4 spi includes the following features: ? full-duplex, three-wire synchronous data transfer ? master or slave operation ? lsb first or msb first data transfer ? seven programmable bit rates ? end of transmission interrupt flag ? write collision flag protection ? wake-up from idle mode ? double speed (ck/2) master spi mode usart can also be used in master spi mode, see ?usart in spi mode? on page 214. the power reduction spi bit, prspi, in ?power reduction register 0 - prr0? on page 46 on page 50 must be written to zero to enable spi module. figure 17-1. spi block diagram (1) note: 1. refer to ?pinout atmega16u4/atmega32u4? on page 3 , and table 10-3 on page 72 for spi pin placement. the interconnection between master and slave cpus with spi is shown in figure 17-2 . the sys- tem consists of two shift registers, and a master clock generator. the spi master initiates the spi2x spi2x divider /2/4/8/16/32/64/128
178 7766f?avr?11/10 atmega16/32u4 communication cycle when pu lling low the slave select ss pin of the desired slave. master and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from mas- ter to slave on the master out ? slave in, mosi, line, and from slave to master on the master in ? slave out, miso, line. after ea ch data packet, the master will synchronize the slave by pulling high the slave select, ss , line. when configured as a master, the spi interface has no automatic control of the ss line. this must be handled by user software before communication can start. when this is done, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the eight bits into the slave. after shifting one byte , the spi clock generator stops, setting the end of transmission flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the buffer register for later use. when configured as a slave, the spi interface will remain sleeping with miso tri-stated as long as the ss pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 17-2. spi master-slave interconnection the system is single buffered in the transmit di rection and double buffered in the receive direc- tion. this means that bytes to be transmitted cannot be written to the spi data register before the entire shift cycle is complet ed. when receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. oth- erwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming signal of the sck pin. to ensure correct sampling of the clock signal, the frequency of the spi clock should never exceed f osc /4. shift enable
179 7766f?avr?11/10 atmega16/32u4 when the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overridden according to table 17-1 . for more details on automatic port overrides, refer to ?alternate port functions? on page 70 . note: 1. see ?alternate functions of port b? on page 72 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initialize the spi as a master and how to perform a simple transmission. ddr_spi in the examples mu st be replaced by the actual data direction register controlling the spi pins. dd_mosi, dd_miso and dd_sck must be replaced by the actual data direction bits for these pins. e.g. if mosi is placed on pin pb5, replace dd_mosi with ddb5 and ddr_spi with ddrb. table 17-1. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input
180 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 181 7766f?avr?11/10 atmega16/32u4 the following code examples show how to initialize the spi as a slave and how to perform a simple reception. note: 1. see ?code examples? on page 8. 17.1 ss pin functionality 17.1.1 slave mode when the spi is configured as a slave, the slave select (ss) pin is always input. when ss is held low, the spi is activated, and miso becomes an output if configured so by the user. all assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 182 7766f?avr?11/10 atmega16/32u4 other pins are inputs. when ss is driven high, all pins are inputs, and the spi is passive, which means that it will not receive incoming data. no te that the spi logic will be reset once the ss pin is driven high. the ss pin is useful for packet/byte synchroniza tion to keep the slave bit counter synchronous with the master clock generator. when the ss pin is driven high, the spi slave will immediately reset the send and receive logic, and drop any partially received data in the shift register. 17.1.2 master mode when the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if ss is configured as an output, the pin is a general output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be held high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is configured as a master with the ss pin defined as an input, the spi system interprets this as another master selecting the spi as a slave and starting to send data to it. to avoid bus contention, the spi system takes the following actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if the spi interrupt is enabled, and the i-bit in sreg is set, the interrupt routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exists a possi- bility that ss is driven low, the interrup t should always check that the mstr bit is still set. if the mstr bit has been cleared by a slave select, it must be set by the user to re-enable spi master mode. 17.1.3 spi control register ? spcr ? bit 7 ? spie: spi interrupt enable this bit causes the spi in terrupt to be executed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable when the spe bit is written to one, the spi is enabled. this bit must be set to enable any spi operations. ? bit 5 ? dord: data order when the dord bit is written to one, the lsb of the data word is transmitted first. when the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi mode when written logic zero. if ss is configured as an input and is driven low while mstr is set, mstr will be cleared, bit 76543210 spie spe dord mstr cpol cpha spr1 spr0 spcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
183 7766f?avr?11/10 atmega16/32u4 and spif in spsr will become set. the user will th en have to set mstr to re-enable spi mas- ter mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high when idle. when cpol is written to zero, sck is low when idle. refer to figure 17-3 and figure 17-4 for an example. the cpol functionality is sum- marized below: ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 17-3 and figure 17-4 for an example. the cpol functionality is summarized below: ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the dev ice configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the oscillator clock frequency f osc is shown in the following table: 17.1.4 spi status register ? spsr table 17-2. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 17-3. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample table 17-4. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 000 f osc / 4 001 f osc / 16 010 f osc / 64 011 f osc / 128 100 f osc / 2 101 f osc / 8 110 f osc / 32 111 f osc / 64 bit 76543210 spif wcol ? ? ? ? ? spi2x spsr read/writerrrrrrrr/w initial value00000000
184 7766f?avr?11/10 atmega16/32u4 ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is dr iven low when the spi is in master mode, this will also set the spif flag. spif is cleared by hardwa re when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data register (spdr) is written during a data transfer. the wcol bit (and the spif bit) are cleared by first reading the spi status register with wcol set, and then accessing the spi data register. ? bit 5..1 ? res: reserved bits these bits are reserved bits in the atmega 16u4/atmega32u4 and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logi c one the spi speed (sck freque ncy) will be doubled when the spi is in master mode (see table 17-4 ). this means that the mini mum sck period will be two cpu clock periods. when the spi is configured as slave, the spi is only guaranteed to work at f osc /4 or lower. the spi interface on the atmega16u4/atmega32u4 is also used for program memory and eeprom downloading or uploading. see page 360 for serial programming and verification. 17.1.5 spi data register ? spdr the spi data register is a read/write register used for data transfer between the register file and the spi shift register. writing to the register initiates data transmission. reading the regis- ter causes the shift register receive buffer to be read. 17.2 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in figure 17-3 and figure 17-4 . data bits are shifted out and latched in on opposite edges of the sck sig- nal, ensuring sufficient time for data signals to st abilize. this is clearly seen by summarizing table 17-2 and table 17-3 , as done below: bit 76543210 msb lsb spdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial valuexxxxxxxxundefined
185 7766f?avr?11/10 atmega16/32u4 figure 17-3. spi transfer format with cpha = 0 figure 17-4. spi transfer format with cpha = 1 table 17-5. cpol functionality leading edge trailing edge spi mode cpol=0, cpha=0 sample (rising) setup (falling) 0 cpol=0, cpha=1 setup (rising) sample (falling) 1 cpol=1, cpha=0 sample (falling) setup (rising) 2 cpol=1, cpha=1 setup (falling) sample (rising) 3 bit 1 bit 6 lsb msb sck (cpol = 0) mode 0 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 2 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 msb first (dord = 0) lsb first (dord = 1) sck (cpol = 0) mode 1 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 3 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 bit 1 bit 6 lsb msb msb first (dord = 0) lsb first (dord = 1)
186 7766f?avr?11/10 atmega16/32u4 18. usart the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. the main features are: ? full duplex operation (independent se rial receive and transmit registers) ? asynchronous or synchronous operation ? flow control cts/rts signals hardware management ? master or slave clocked synchronous operation ? high resolution baud rate generator ? supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits ? odd or even parity generation and parity check supported by hardware ? data overrun detection ? framing error detection ? noise filtering includes false start bit detection and digital low pass filter ? three separate interrupts on tx complete, tx data register empty and rx complete ? multi-processor communication mode ? double speed asynchronous communication mode . 18.1 overview a simplified block diagram of the usart transmitter is shown in figure 18-1 on page 187 . cpu accessible i/o registers and i/o pins are shown in bold.
187 7766f?avr?11/10 atmega16/32u4 figure 18-1. usart block diagram (1) note: 1. see ?pinout atmega16u4/atmega32u4? on page 3 , table 10-8 on page 77 and for usart pin placement. the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter and receiver. control registers are shared by all units. the clock generation logic consis ts of synchronization logic fo r external clock input used by synchronous slave operation, and the baud rate generator. the xckn (transfer clock) pin is only used by synchronous transfer mode. the transmi tter consists of a single write buffer, a serial shift register, parity generator and cont rol logic for handling different serial frame for- mats. the write buffer allows a continuous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udrn). the receiver supports the same frame formats as the transmitter, and can detect frame error, data overrun and parity errors. 18.2 clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usartn supports four modes of clock opera tion: normal asynchronous, double speed asyn- chronous, master synchronous and slave synchronous mode. the umseln bit in usart control and status register c (ucsrnc) selects between asynchronous and synchronous operation. double speed (asynchronous mode only) is controlled by the u2xn found in the parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker data bus osc sync logic clock generator transmitter receiver
188 7766f?avr?11/10 atmega16/32u4 ucsrna register. when using synchronous mode (umseln = 1), the data direction register for the xckn pin (ddr_xckn) controls whether the clock source is internal (master mode) or external (slave mode). the xckn pin is only active when using synchronous mode. figure 18-2 shows a block diagram of the clock generation logic. figure 18-2. clock generation logic, block diagram signal description: txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. f osc xtal pin frequency (system clock). 18.2.1 internal clock generation ? the baud rate generator internal clock generation is used for the as ynchronous and the synchronous master modes of operation. the description in this section refers to figure 18-2 . the usart baud rate register (ubrrn) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at system clock (f osc ), is loaded with the ubrrn value each time the counter has counted down to zero or when the ubrrln register is written. a clock is gene rated each time the counter reaches zero. this clock is the baud rate generator clock output (= f osc /(ubrrn+1)). the transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. the baud rate generator out- put is used directly by the receiver?s clock an d data recovery units. however, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the umseln, u2xn and ddr_xckn bits. prescaling down-counter /2 ubrr /4 /2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxclk 0 1 1 0 edge detector ucpol
189 7766f?avr?11/10 atmega16/32u4 table 18-1 contains equations for calculating the baud rate (in bits per second) and for calculat- ing the ubrrn value for each mode of operation using an internally generated clock source. note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrhn and ubrrln registers, (0-4095) some examples of ubrrn values for some system clock frequencies are found in table 18-9 on page 210 . 18.2.2 double speed operation (u2xn) the transfer rate can be doubled by setting the u2xn bit in ucsrna. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. table 18-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous normal mode (u2xn = 0) asynchronous double speed mode (u2xn = 1) synchronous master mode baud f osc 16 ubrr n 1 + () ----------------------------------------- - = ubrr n f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? =
190 7766f?avr?11/10 atmega16/32u4 18.2.3 external clock external clocking is used by the synchronous sl ave modes of operation. the description in this section refers to figure 18-2 for details. external clock input from the xckn pin is sample d by a synchronization register to minimize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process intro- duces a two cpu clock period delay and therefore the maximum external xckn clock frequency is limited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recommended to add some margin to avoid possible loss of data due to frequency variations. 18.2.4 synchronous clock operation when synchronous mode is used (umseln = 1), th e xckn pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. the basic principle is that data input (on rxdn) is sampled at the opposite xckn clock edge of the edge the data output (txdn) is changed. figure 18-3. synchronous mode xckn timing. the ucpoln bit ucrsc selects which xckn cloc k edge is used for data sampling and which is used for data change. as figure 18-3 shows, when ucpoln is zero the data will be changed at rising xckn edge and sampled at falling xckn edge. if ucpoln is set, the data will be changed at falling xckn edge and samp led at rising xckn edge. 18.3 frame formats a serial frame is defined to be one character of da ta bits with synchronizat ion bits (start and stop bits), and optionally a parity bi t for error checking. the usart accepts all 30 combinations of the following as valid frame formats: ? 1 start bit ? 5, 6, 7, 8, or 9 data bits ? no, even or odd parity bit ? 1 or 2 stop bits f xck f osc 4 ----------- < rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample
191 7766f?avr?11/10 atmega16/32u4 a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with t he most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. when a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. figure 18-4 illustrates the possible combinations of th e frame formats. bits inside brackets are optional. figure 18-4. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. sp stop bit, always high. idle no transfers on the communication line (rxdn or txdn). an idle line must be high. the frame format used by th e usart is set by the ucszn2:0, upmn1:0 and usbsn bits in ucsrnb and ucsrnc. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt a ll ongoing communication for both the receiver and transmitter. the usart character size (ucszn2:0) bits select the number of data bits in the frame. the usart parity mode (upmn1:0) bits enable and set the type of parity bit. the selection between one or two stop bits is done by the usart stop bit select (usbsn) bit. the re ceiver ignores the second stop bit. an fe (f rame error) will theref ore only be detected in the cases where the first stop bit is zero. 18.3.1 parity bit calculation the parity bit is calculated by do ing an exclusive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the re lation between the parity bit and data bits is as follows:: p even parity bit using even parity p odd parity bit using odd parity d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = =
192 7766f?avr?11/10 atmega16/32u4 18.4 usart initialization the usart has to be initialized before any communication can take place. the initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. the txcn flag can be used to check that the transmitter has completed all transfers, and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txcn flag must be cleared before each transmission (before udrn is written) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the exampl es assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. note: 1. see ?code examples? on page 8. more advanced initialization routines can be made that include frame format as parameters, dis- able interrupts and so on. however, many appl ications use a fixed setting of the baud and control registers, and for these types of applicati ons the initialization code can be placed directly in the main routine, or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate out ubrrhn, r17 out ubrrln, r16 ; enable receiver and transmitter ldi r16, (1<>8); ubrrln = ( unsigned char )baud; /* enable receiver and transmitter */ ucsrnb = (1< 193 7766f?avr?11/10 atmega16/32u4 18.5 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrnb register. when the transmitter is enabled, the normal port operation of the txdn pin is overrid- den by the usart and given the function as t he transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any transmissions. if syn- chronous operation is used, the clock on the xckn pi n will be overridden and used as transmission clock. 18.5.1 sending frames with 5 to 8 data bit a data transmission is initiated by loading the transmit buffer with the data to be transmitted. the cpu can load the transmit buffer by writing to the udrn i/o location. the buffered data in the transmit buffer will be moved to the shift register wh en the shift register is ready to send a new frame. the shift register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. when the shift register is loaded with new data, it will transf er one complete frame at the ra te given by the baud register, u2xn bit or by xckn depending on mode of operation. the following code examples show a simple usart transmit function based on polling of the data register empty (udren) flag. when using frames with less than eight bits, the most sig- nificant bits written to the udrn are ignored. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16 . note: 1. see ?code examples? on page 8. the function simply waits for the transmit buffer to be em pty by checking the udren flag, before loading it wit h new data to be transmitted. if the da ta register empty in terrupt is utilized, the interrupt routine writes the data into the buffer. assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; put data (r16) into buffer, sends the data out udrn,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 194 7766f?avr?11/10 atmega16/32u4 18.5.2 sending frames with 9 data bit if 9-bit characters are used (ucszn = 7), the ninth bit must be written to the txb8 bit in ucsrnb before the low byte of the character is written to udrn. the following code examples show a transmit function that handles 9-bit characters. for the assembly code, the data to be sent is assumed to be stored in registers r17:r16. notes: 1. these transmit functions are written to be general functions. they can be optimized if the con- tents of the ucsrnb is static. for example, only the txb8 bit of the ucsrnb register is used after initialization. 2. see ?code examples? on page 8. the ninth bit can be used for indicating an address frame when using multi processor communi- cation mode or for other protocol handling as for example synchronization. 18.5.3 transmitter flags and interrupts the usart transmitter has two flags that indi cate its state: usart data register empty (udren) and transmit complete (txcn). both flags can be used for generating interrupts. the data register empty (udren) flag indicates whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet be en moved into the shift register. for compat- ibility with future devices, alwa ys write this bit to zero when writing the ucsrna register. assembly code example (1)(2) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrnb,txb8 sbrc r17,0 sbi ucsrnb,txb8 ; put lsb data (r16) into buffer, sends the data out udrn,r16 ret c code example (1)(2) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 195 7766f?avr?11/10 atmega16/32u4 when the data register empty interrupt enable ( udrien) bit in ucsrnb is written to one, the usart data register empty inte rrupt will be executed as long as udren is set (provided that global interrupts are enabled). udren is clea red by writing udrn. when interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to udrn in order to clear udren or disable the data register empty interrupt, otherwise a new interrupt will occur once the in terrupt routin e terminates. the transmit complete (txcn) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location . the txcn flag is usef ul in half-duplex commu- nication interfaces (like the rs-485 standard) , where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. when the transmit compete interrupt enable (txcien) bit in ucsrnb is set, the usart transmit complete interrupt will be executed when the txcn flag becomes set (provided that global interrupts are enabled). when the transmit complete interrupt is used, the interrupt han- dling routine does not have to clear the txcn fl ag, this is done automatically when the interrupt is executed. 18.5.4 parity generator the parity generator calculates the parity bit for the serial frame data. when parity bit is enabled (upmn1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. 18.5.5 disabling the transmitter the disabling of the tran smitter (setting the txen to zero ) will not become effective until ongo- ing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. when disabled, the transmitter will no longer override the txdn pin. 18.6 data reception ? the usart receiver the usart receiver is enabled by writi ng the receive enable (rxenn) bit in the ucsrnb register to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden by the usart and given the func tion as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before any serial reception can be done. if synchronous operation is used, the cloc k on the xckn pin will be used as transfer clock. 18.6.1 receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at the baud rate or xckn cl ock, and shifted into the receive shift register until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. when the first stop bit is received, i.e., a complete serial frame is present in the receive shift register, the contents of the shift register will be moved into the rece ive buffer. the receive buffer can then be read by reading the udrn i/o location. the following code example shows a simple us art receive function based on polling of the receive complete (rxcn) flag. when using frames with less than eight bits the most significant
196 7766f?avr?11/10 atmega16/32u4 bits of the data read from the udrn will be masked to zero. th e usart has to be initialized before the function can be used. note: 1. see ?code examples? on page 8. the function simply waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value. 18.6.2 receiving frames with 9 data bits if 9-bit characters are used (ucszn=7) the ninth bit must be read from the rxb8n bit in ucsrnb before reading the low bits from the udrn. this rule applies to the fen, dorn and upen status flags as well. read status fr om ucsrna, then data from udrn. reading the udrn i/o location will change the state of the re ceive buffer fifo and consequently the txb8n, fen, dorn and upen bits, which a ll are stored in the fifo, will change. the following code example shows a simple usart receive function that handles both nine bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsrna & (1< 197 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. the receive function example reads all the i/o r egisters into the register file before any com- putation is done. this gives an optimal receive buffer utilization since the bu ffer location read will be free to accept new data as early as possible. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get status and 9th bit, then data from buffer in r18, ucsrna in r17, ucsrnb in r16, udrn ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
198 7766f?avr?11/10 atmega16/32u4 18.6.3 receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxcn) flag indicates if there are unread data present in the receive buf- fer. this flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled (rxenn = 0), the receive buffer will be flushed and cons equently the rxcn bit will become zero. when the receive complete interrupt enable (r xcien) in ucsrnb is set, the usart receive complete interrupt will be executed as long as the rxcn flag is se t (provided that global inter- rupts are enabled). when interrupt-driven data reception is used, the receive complete routine must read the received data from udrn in order to clear the rxcn flag, otherwise a new inter- rupt will occur once the inte rrupt routine terminates. 18.6.4 receiver error flags the usart receiver has three error flags: frame error (fen), data overrun (dorn) and parity error (upen). all can be accessed by reading ucsrna. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buffering of the error flags, the ucsrna must be read before the receive buffer (udrn), since reading the udrn i/o location change s the buffer read location. another equality for the error flags is that they can not be altered by software doing a write to the flag location. however, all flags must be set to zero when the ucsrna is written for upward compatibility of future usart impl ementations. none of the error flags can genera te interrupts. the frame error (fen) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fen flag is zero when the stop bit was correctly read (as one), and the fen flag will be one when the stop bit was incorrect (zero). this flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. the fen flag is not affected by the setting of the u sbsn bit in ucsrnc since the receiver ignores all, except for the first, stop bits. for compatibility with future devices, always set this bit to zero when writing to ucsrna. the data overrun (dorn) flag indicates data loss due to a receiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters), it is a new character wait- ing in the receive shift register, and a new start bit is detected. if the dorn flag is set there was one or more serial frame lost between the frame last read from udrn, and the next frame read from udrn. for compatibility wi th future devices, always write this bit to zero when writing to ucsrna. the dorn flag is cleared when t he frame received was successfully moved from the shift register to the receive buffer. the parity error (upen) flag indicates that the next frame in the receive buffer had a parity error when received. if parity check is not enabled the upen bit will always be read zero. for compatibility with future devices, always set this bit to zero when writing to ucsrna. for more details see ?parity bit calculation? on page 191 and ?parity checker? on page 198 . 18.6.5 parity checker the parity checker is active when the high usart parity mode (upmn1) bit is set. type of par- ity check to be performed (odd or even) is selected by the upmn0 bit. when enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. the result of the check is stored in the receive buffer together with the received data and stop bits. the parity error (upen) flag can then be read by software to check if the frame had a parity error.
199 7766f?avr?11/10 atmega16/32u4 the upen bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. 18.6.6 disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be lost. when disabled (i .e., the rxenn is set to zero) the receiver will no longer override the normal function of the rxdn port pin. the receiver buffer fifo will be flushed when the receiver is disabled. remaining data in the buffer will be lost 18.6.7 flushing the receive buffer the receiver buffer fifo will be fl ushed when the receiver is disa bled, i.e., the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for in stance an error conditi on, read the udrn i/o location until the rxcn flag is cleared. the following code example shows how to flush the receive buffer. note: 1. see ?code examples? on page 8. 18.7 asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchronous data reception. the clock recovery logic is used fo r synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxdn pin. the data recovery logic sam- ples and low pass filters each incoming bit, ther eby improving the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the inter- nal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 18.7.1 asynchronous clock recovery the clock recovery logic synchronizes internal clock to the incoming serial frames. figure 18-5 illustrates the sampling process of th e start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. the hor- izontal arrows illustrate the sy nchronization variation due to t he sampling process. note the larger time variation when using the double speed mode (u2xn = 1) of operation. samples denoted zero are samples done when the rxdn line is idle (i.e., no communication activity). assembly code example (1) usart_flush: sbis ucsrna, rxcn ret in r16, udrn rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsrna & (1< 200 7766f?avr?11/10 atmega16/32u4 figure 18-5. start bit sampling when the clock recovery logic detects a high (idle) to low (start) transitio n on the rxdn line, the start bit detection sequence is initiated. let sample 1 denote the first zero-sample as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for normal mode, and sam- ples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. if two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transition. if however, a valid start bit is detected, the clock recov- ery logic is synchronized and the data recove ry can begin. the sy nchronization process is repeated for each start bit. 18.7.2 asynchronous data recovery when the receiver clock is synchronized to the start bit, the data recovery can begin. the data recovery unit uses a state machine that has 16 states for each bit in normal mode and eight states for each bit in double speed mode. figure 18-6 shows the sampling of the data bits and the parity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 18-6. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majori ty voting of the logic value to the three samples in the center of the received bit. the center samples are emphasized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all three samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxdn pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. note that the receiver only uses the first stop bit of a frame. figure 18-7 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. 1234567 8 9 10 11 12 13 14 15 16 12 start idle 0 0 bit 0 3 123 4 5 678 12 0 rxd sample (u2x = 0) sample (u2x = 1) 1234567 8 9 10 11 12 13 14 15 16 1 bit n 123 4 5 678 1 rxd sample (u2x = 0) sample (u2x = 1)
201 7766f?avr?11/10 atmega16/32u4 figure 18-7. stop bit sampling and ne xt start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 va lue, the frame error (fen) flag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for normal speed mode, the first low level sample can be at point marked (a) in figure 18-7 . for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the ear ly start bit detection influences the operational range of the receiver. 18.7.3 asynchronous operational range the operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see table 18-2 ) base frequency, the receiver will not be abl e to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. d sum of character size and parity size (d = 5 to 10 bit) s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. table 18-2 and table 18-3 list the maximum receiver baud rate error that can be tolerated. note that normal speed mode has higher toleration of baud rate variations. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ - = r fast d 2 + () s d 1 + () ss m + ----------------------------------- =
202 7766f?avr?11/10 atmega16/32u4 the recommendations of the maximum receiver baud rate error was made under the assump- tion that the receiver and transmitter equally divides the maximum total error. there are two possible sources fo r the receivers baud rate erro r. the receiver?s system clock (xtal) will always have some minor instabilit y over the supply voltage range and the tempera- ture range. when using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the b aud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. 18.8 multi-processor communication mode setting the multi-processor communication m ode (mpcmn) bit in ucsrna enables a filtering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put in to the receive buffer. this effectively reduces the number of incoming frames that has to be handled by the cpu, in a system with multiple mcus that communicate via the same serial bu s. the transmitter is unaffected by the mpcmn setting, but has to be used diffe rently when it is a part of a system utilizing the multi-processor communication mode. if the receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indi- cates if the frame contains data or address information. if the receiver is set up for frames with table 18-2. recommended maximum receiver baud rate error for normal speed mode (u2xn = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11/-5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 18-3. recommended maximum receiver baud rate error for double speed mode (u2xn = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104,35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
203 7766f?avr?11/10 atmega16/32u4 nine data bits, then the ninth bit (rxb8n) is used for identifying address and data frames. when the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slave mcu has been addressed, it will rece ive the following data frames as normal, while the other slave mcus will ignore the received frames until another address frame is received. 18.8.1 using mpcmn for an mcu to act as a master mcu, it can us e a 9-bit character frame format (ucszn = 7). the ninth bit (txb8n) must be set when an address frame (txb8n = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communication mode: 1. all slave mcus are in multi-processor communication mode (mpcmn in ucsrna is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxcn flag in ucsrna will be set as normal. 3. each slave mcu reads the udrn register and determines if it has been selected. if so, it clears the mpcmn bit in ucsrna, otherwise it waits for the next address byte and keeps the mpcmn setting. 4. the addressed mcu will receive all data fram es until a new address frame is received. the other slave mcus, which still have the mp cmn bit set, will ignore the data frames. 5. when the last data frame is received by the addressed mcu, the addressed mcu sets the mpcmn bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5- to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full- duplex operation difficult since the transmitter a nd receiver uses the same character size set- ting. if 5- to 8-bit character frames are used, the transmitter must be set to use two stop bit (usbsn = 1) since the first stop bit is used for indicating the frame type. do not use read-modify-write in structions (sbi and cbi) to set or clear the mpcmn bit. the mpcmn bit shares the same i/o location as the txcn flag and this might accidentally be cleared when using sbi or cbi instructions. 18.9 hardware flow control the hardware flow control can be enabled by software. cts : (clear to send) rts : (request to send) txd rts txd rxd host rxd cts cts rts atmega16u4/atm
204 7766f?avr?11/10 atmega16/32u4 18.9.1 receiver flow control the reception flow can be controlled by hardware using the rts pin. the aim of the flow control is to inform the external transmitter when the inte rnal receive fifo is full. thus the transmitter can stop sending characters. rts usage and so associated flow control is enabled using rtsen bit in ucsrnd. figure 18-8. shows a reception example. figure 18-8. reception flow control waveform example figure 18-9. rts behavior rts will rise at 2/3 of the last received stop bit if the receive fifo is full. to ensure reliable transmissions, even after a rts rise, an extra-data can still be received and stored in the rece ive shift register. 18.9.2 transmission flow control the transmission flow can be controlled by hardware using the cts pin controlled by the exter- nal receiver. the aim of the flow control is to stop transmission when the receiver is full of data (cts = 1). cts usage and so associated flow control is enabled using ctsen bit in ucsrnd. the cts pin is sampled at each cpu write and at the middle of the last stop bit that is currently being sent. figure 18-10. cts behavior rts rxd c1 c2 0 1 2 fifo 1 cpu read index c3 1 0 rts rxd start byte0 stop start byte1 stop read from cpu start byte2 1 additional byte may be sent if the transmitter misses the rts trig cts txd start byte0 stop start byte1 stop start byte2 sample sample write from cpu sample
205 7766f?avr?11/10 atmega16/32u4 18.10 usart regist er description 18.10.1 usart i/o data register n? udrn the usart transmit data buffer register and usart receive data buffer registers share the same i/o address re ferred to as usart data register or udrn. the transmit data buffer reg- ister (txb) will be the destination for data wri tten to the udrn register location. reading the udrn register location will retu rn the contents of the receiv e data buffer register (rxb). for 5-, 6-, or 7-bit char acters the upper unu sed bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written when the udren flag in the ucsrna register is set. data written to udrn wh en the udren flag is not set, will be ignored by the usart transmit- ter. when data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the transmit shift regist er when the shift register is empty. then the data will be serially transmitted on the txdn pin. the receive buffer consists of a two level fifo . the fifo will change its state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify- write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will change the state of the fifo. 18.10.2 usart control and status register a ? ucsrna ? bit 7 ? rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread dat a). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit will become zero. the rxcn flag can be used to generate a receive complete interr upt (see description of the rxcien bit). ? bit 6 ? txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 ? udren: usart data register empty the udren flag indicates if the transmit buff er (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrien bit). udren is set after a reset to indicate that the transmitter is ready. bit 76543210 rxb[7:0] udrn (read) txb[7:0] udrn (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 rxcn txcn udren fen dorn upen u2xn mpcmn ucsrna read/writerr/wrrrrr/wr/w initial value00100000
206 7766f?avr?11/10 atmega16/32u4 ? bit 4 ? fen: frame error this bit is set if the next character in the receive buffer had a frame error when received. i.e., when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive buffer (udrn) is read. the fen bit is zero when the stop bit of received data is one. always set this bit to ze ro when writing to ucsrna. ? bit 3 ? dorn: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two characters), it is a new char acter waiting in the receive shift register, and a new start bit is detected. this bi t is valid until the receive buffer (udrn) is read . always set this bit to zero when writing to ucsrna. ? bit 2 ? upen: usart parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 1 ? u2xn: double the usart transmission speed this bit only has effect for the asynchronous operation. write this bit to zero when using syn- chronous operation. writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively dou- bling the transfer rate for asynchronous communication. ? bit 0 ? mpcmn: multi-processor communication mode this bit enables the multi-processor communica tion mode. when the mpcmn bit is written to one, all the incoming frames received by the usart receiver that do not contain address infor- mation will be ignored. the transmitter is unaffe cted by the mpcmn setting. for more detailed information see ?multi-processor communication mode? on page 202 . 18.10.3 usart control and status register n b ? ucsrnb ? bit 7 ? rxcien: rx comp lete interrupt enable n writing this bit to one enables interrupt on the rxcn flag. a usart rece ive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 ? txcien: tx complete interrupt enable n writing this bit to one enables interrupt on the txcn flag. a usart trans mit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 ? udrien: usart data register empty interrupt enable n writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrien bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. bit 7 6 5 4 3 2 1 0 rxcien txcien udrien rxenn txenn ucszn2 rxb8n txb8n ucsrnb read/write r/w r/w r/w r/w r/w r/w r r/w initial value 0 0 0 0 0 0 0 0
207 7766f?avr?11/10 atmega16/32u4 ? bit 4 ? rxenn: receiver enable n writing this bit to one enables the usart receiv er. the receiver will override normal port oper- ation for the rxdn pin when enabled. disab ling the receiver will fl ush the receive buffer invalidating the fen, dorn, and upen flags. ? bit 3 ? txenn: transmitter enable n writing this bit to one enables the usart tr ansmitter. the transmitter will override normal port operation for the txdn pin when enabled. the di sabling of the transmitter (writing txenn to zero) will not become effective until ongoing a nd pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2 ? ucszn2: character size n the ucszn2 bits combined with the ucszn1:0 bit in ucsrnc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8n: receive data bit 8 n rxb8n is the ninth data bit of the received char acter when operating with serial frames with nine data bits. must be read before reading the low bits from udrn. ? bit 0 ? txb8n: transmit data bit 8 n txb8n is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. must be written before writing the low bits to udrn. 18.10.4 usart control and status register n c ? ucsrnc ? bits 7:6 ? umseln1:0 usart mode select these bits select the mode of operation of the usartn as shown in table 18-4 . note: 1. see ?usart in spi mode? on page 214 for full description of the master spi mode (mspim) operation ? bits 5:4 ? upmn1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmitter will automatically generate and send the parity of th e transmitted data bits within each frame. the bit 7 6 5 4 3 2 1 0 umseln1 umseln0 upmn1 upmn0 usbsn ucszn1 ucszn0 ucpoln ucsrnc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 18-4. umseln bit settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim) (1)
208 7766f?avr?11/10 atmega16/32u4 receiver will generate a parity va lue for the incoming data and co mpare it to th e upmn setting. if a mismatch is detected, the upen flag in ucsrna will be set. ? bit 3 ? usbsn: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucszn1:0: character size the ucszn1:0 bits combined with the ucszn2 bit in ucsrnb sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 0 ? ucpoln: clock polarity this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpoln bit sets the relationship between data output change and data input sample, and the synchronous clock (xckn). table 18-5. upmn bit settings upmn1 upmn0 parity mode 0 0 disabled 01reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 18-6. usbs bit settings usbsn stop bit(s) 01-bit 12-bit table 18-7. ucszn bit settings ucszn2 ucszn1 ucszn0 character size 0005-bit 0016-bit 0107-bit 0118-bit 100reserved 101reserved 110reserved 1119-bit table 18-8. ucpoln bit settings ucpoln transmitted data changed (output of txdn pin) received data sampled (input on rxdn pin) 0 rising xckn edge falling xckn edge 1 falling xckn edge rising xckn edge
209 7766f?avr?11/10 atmega16/32u4 18.10.5 usart control and status register n d? ucsrnd ? bits 7:2 ? reserved bits these bits are reserved and will be read as ?0?. do not set these bits. ? bits 1 ? ctsen: uart cts signal enable set this bit by firmware to enable the transmission flow control signal (cts ). transmission will be enabled only if cts input = 0. clear this bit to disabl e the transmission flow control signal. transmission will occur without hard ware condition. data direction register bit must be correctly clear to enable the pin as an input. ? bits 0 ? rtsen: uart rts signal enable set this bit by firmware to enable the reception fl ow control signal (rts). in this case the rts line will automatically rise when the fifo is full. clear this bit to disable the reception flow control signal. data direction register bit must be correctly set to enable the pin as an output. 18.10.6 usart baud rate registers ? ubrrln and ubrrhn ? bit 15:12 ? reserved bits these bits are reserved for future use. for compatibility with future devices, these bit must be written to zero when ubrrh is written. ? bit 11:0 ? ubrr11:0: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrh contains the four most significant bits, and the ubrrl contains th e eight least significant bits of the usart baud rate. ongoing transmissions by the transmitter and receiver will be corrupted if th e baud rate is changed. writing ubrrl will tr igger an immediate update of the baud rate prescaler. 18.11 examples of ba ud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asyn- chronous operation can be generated by using the ubrr settings in table 18-9 to table 18-12 . ubrr values which yield an actual baud rate diffe ring less than 0.5% from the target baud rate, are bold in the table. higher error ratings are acceptable, but the receiver will have less noise bit 7 6 5 4 3 2 1 0 ? ? ? ? ? ? ctsen rtsen ucsrnd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 1514131211109 8 ? ? ? ? ubrr[11:8] ubrrhn ubrr[7:0] ubrrln 76543210 read/writerrrrr/wr/wr/wr/w r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 00000000
210 7766f?avr?11/10 atmega16/32u4 resistance when the error ratings are high, especially for large serial frames (see ?asynchronous operational range? on page 201 ). the error values are calculat ed using the following equation: error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? = table 18-9. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000 mhz f osc = 1.8432 mhz f osc = 2.0000 mhz u2xn = 0u2xn = 1u2xn = 0u2xn = 1u2xn = 0u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 250.2%510.2%470.0%950.0%510.2%1030.2% 4800 120.2%250.2%230.0%470.0%250.2%510.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k??????00.0%???? 250k??????????00.0% max. (1) 62.5 kbps 125 kbps 115.2 kbps 2 30.4 kbps 125 kbps 250 kbps 1. ubrr = 0, error = 0.0%
211 7766f?avr?11/10 atmega16/32u4 table 18-10. examples of ubrrn settings for common ly used oscillator frequencies (continued) baud rate (bps) f osc = 3.6864 mhz f osc = 4.0000 mhz f osc = 7.3728 mhz u2xn = 0u2xn = 1u2xn = 0u2xn = 1u2xn = 0u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 230.0%470.0%250.2%510.2%470.0%950.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ??????????0-7.8% max. (1) 230.4 kbps 460.8 kbps 250 kbps 0.5 mbps 460.8 kbps 921.6 kbps 1. ubrr = 0, error = 0.0%
212 7766f?avr?11/10 atmega16/32u4 table 18-11. examples of ubrrn settings for common ly used oscillator frequencies (continued) baud rate (bps) f osc = 8.0000 mhz f osc = 11.0592 mhz f osc = 14.7456 mhz u2xn = 0u2xn = 1u2xn = 0u2xn = 1u2xn = 0u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ? ? ? 0 -7.8% 1 -7.8% max. (1) 0.5 mbps 1 mbps 691.2 kbps 1.3824 mbps 921.6 kbps 1.8432 mbps 1. ubrr = 0, error = 0.0%
213 7766f?avr?11/10 atmega16/32u4 table 18-12. examples of ubrrn settings for common ly used oscillator frequencies (continued) baud rate (bps) f osc = 16.0000 mhz f osc = 18.4320 mhz f osc = 20.0000 mhz u2xn = 0u2xn = 1u2xn = 0u2xn = 1u2xn = 0u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 416 -0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0% 4800 207 0.2% 416 -0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0% 9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2% 14.4k 68 0.6% 138 -0.1% 79 0.0% 159 0.0% 86 -0.2% 173 -0.2% 19.2k 51 0.2% 103 0.2% 59 0.0% 119 0.0% 64 0.2% 129 0.2% 28.8k 34 -0.8% 68 0.6% 39 0.0% 79 0.0% 42 0.9% 86 -0.2% 38.4k 25 0.2% 51 0.2% 29 0.0% 59 0.0% 32 -1.4% 64 0.2% 57.6k 16 2.1% 34 -0.8% 19 0.0% 39 0.0% 21 -1.4% 42 0.9% 76.8k 12 0.2% 25 0.2% 14 0.0% 29 0.0% 15 1.7% 32 -1.4% 115.2k 8 -3.5% 16 2.1% 9 0.0% 19 0.0% 10 -1.4% 21 -1.4% 230.4k 3 8.5% 8 -3.5% 4 0.0% 9 0.0% 4 8.5% 10 -1.4% 250k 3 0.0% 7 0.0% 4 -7.8% 8 2.4% 4 0.0% 9 0.0% 0.5m 1 0.0% 3 0.0% ? ? 4 -7.8% ? ? 4 0.0% 1m 0 0.0% 1 0.0% ? ? ? ? ? ? ? ? max. (1) 1 mbps 2 mbps 1.152 mbps 2.3 04 mbps 1.25 mbps 2.5 mbps 1. ubrr = 0, error = 0.0%
214 7766f?avr?11/10 atmega16/32u4 19. usart in spi mode the universal synchronous and asynchronous serial receiver and transmitter (usart) can be set to a master spi compliant mode of operation. the master spi mode (mspim) has the follow- ing features: ? full duplex, three-wire synchronous data transfer ? master operation ? supports all four spi modes of operation (mode 0, 1, 2, and 3) ? lsb first or msb first data tran sfer (configurable data order) ? queued operation (double buffered) ? high resolution baud rate generator ? high speed operatio n (fxckmax = fck/2) ? flexible interrupt generation 19.1 overview setting both umseln1:0 bits to one enables the usart in mspim logic. in this mode of opera- tion the spi master control logic takes direct control over the usart resources. these resources include the transmitter and receiver shift register and buffers, and the baud rate gen- erator. the parity generator and checker, the data and clock recovery logic, and the rx and tx control logic is disabled. the usart rx and tx control logic is replaced by a common spi transfer control logic. however, the pin control l ogic and interrupt generation logic is identical in both modes of operation. the i/o register locations are the same in both modes. however, some of the functionality of the control registers changes when using mspim. 19.2 clock generation the clock generation logic generates the base clock for the transmitter and receiver. for usart mspim mode of operation only internal cl ock generation (i.e. master operation) is sup- ported. the data direction register for the xckn pin (ddr_xckn) must therefore be set to one (i.e. as output) for th e usart in mspim to operate correc tly. preferably the ddr_xckn should be set up before the usart in mspim is enabled (i.e. txenn and rxenn bit set to one). the internal clock generation used in mspim mode is identical to the usart synchronous mas- ter mode. the baud rate or ubrrn setting can therefore be calculated using the same equations, see table 19-1 : table 19-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrrn value synchronous master mode baud f osc 2 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? =
215 7766f?avr?11/10 atmega16/32u4 note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrnh and ubrrnl registers, (0-4095) 19.3 spi data modes and timing there are four combinations of xckn (sck) phase and polarity with respect to serial data, which are determined by control bits ucphan and ucpoln. the data transfer timing diagrams are shown in figure 19-1 . data bits are shifted out and latched in on opposite edges of the xckn signal, ensuring sufficient time for data sign als to stabilize. the ucpoln and ucphan function- ality is summarized in table 19-2 . note that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. figure 19-1. ucphan and ucpoln data transfer timing diagrams. 19.4 frame formats a serial frame for the mspim is defined to be one character of 8 data bits. the usart in mspim mode has two valid frame formats: ? 8-bit data with msb first ? 8-bit data with lsb first a frame starts with the least or most significant data bit. then the next data bits, up to a total of eight, are succeeding, ending with the most or least significant bit accordingly. when a complete frame is transmitted, a new frame can directly follow it, or the communication line can be set to an idle (high) state. table 19-2. ucpoln and ucphan functionality- ucpoln ucphan spi mode leading edge trailing edge 0 0 0 sample (rising) setup (falling) 0 1 1 setup (rising) sample (falling) 1 0 2 sample (falling) setup (rising) 1 1 3 setup (falling) sample (rising) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) ucpol=0 ucpol=1 ucpha=0 ucpha=1
216 7766f?avr?11/10 atmega16/32u4 the udordn bit in ucsrnc sets the frame form at used by the usart in mspim mode. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt all ongoin g communication for both th e receiver and transmitter. 16-bit data transfer can be achieved by writing two data bytes to udrn. a uart transmit com- plete interrupt will then signal that the 16-bit value ha s been shifted out. 19.4.1 usart mspim initialization the usart in mspim mode has to be initialized before any communication can take place. the initialization process normally consists of setting the baud rate, setting master mode of operation (by setting ddr_xckn to one), setting frame format and enabling the transmitter and the receiver. only the transmitter can operate independently. for interrupt driven usart opera- tion, the global interrupt flag should be clear ed (and thus interrupts globally disabled) when doing the initialization. note: to ensure immediate initialization of the xckn output the baud-rate register (ubrrn) must be zero at the time the transmitter is enabled. contrary to the normal mode usart operation the ubrrn must then be written to the desired value after the transmitter is enabled, but before the first transmission is started. setting ubrrn to ze ro before enabling the transmitter is not neces- sary if the initialization is done immediatel y after a reset since ubrrn is reset to zero. before doing a re-initialization with changed baud rate, data mode, or frame format, be sure that there is no ongoing transmissions during the per iod the registers are changed. the txcn flag can be used to check that the transmitter has completed all transfers, and the rxcn flag can be used to check that there are no unread data in the receive buffer. note that the txcn flag must be cleared bef ore each transmission (before udrn is wri tten) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the examples assume polling (no interrupts enabled). the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers.
217 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. 19.5 data transfer using the usart in mspi mode requires the tr ansmitter to be enabled, i.e. the txenn bit in the ucsrnb register is set to one. when the transmitter is enabled, the normal port operation of the txdn pin is overridden and given the func tion as the transmitter's serial output. enabling the receiver is optional and is done by setting the rxenn bit in the ucsrnb register to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden and given the function as the receiver's se rial input. the xckn will in both cases be used as the transfer clock. assembly code example (1) usart_init: clr r18 out ubrrnh,r18 out ubrrnl,r18 ; setting the xckn port pin as output, enables master mode. sbi xckn_ddr, xckn ; set mspi mode of operation and spi data mode 0. ldi r18, (1< 218 7766f?avr?11/10 atmega16/32u4 after initialization the usart is re ady for doing data transfers. a data transfer is initiated by writ- ing to the udrn i/o location. this is the ca se for both sending and receiving data since the transmitter controls the transfer clock. the data written to udrn is moved from the transmit buf- fer to the shift register when the shift register is ready to send a new frame. note: to keep the input buffer in sync with the number of data bytes transmitted, the udrn register must be read once for each byte transmitted. the input buffer operation is identical to normal usart mode, i.e. if an overflow occurs the character last received will be lost, not the first data in the buf- fer. this means that if four bytes are transferred, byte 1 first, then byte 2, 3, and 4, and the udrn is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte 1. the following code examples show a simple u sart in mspim mode transfer function based on polling of the data register empty (udren) flag and the receive complete (rxcn) flag. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stor ed in register r16 and the data received will be available in the same register (r16) after the function returns. the function simply waits for the transmit buffer to be em pty by checking the udren flag, before loading it with new data to be transmitted. the function then waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value. assembly code example (1) usart_mspim_transfer: ; wait for empty transmit buffer sbis ucsrna, udren rjmp usart_mspim_transfer ; put data (r16) into buffer, sends the data out udrn,r16 ; wait for data to be received usart_mspim_wait_rxcn: sbis ucsrna, rxcn rjmp usart_mspim_wait_rxcn ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 219 7766f?avr?11/10 atmega16/32u4 note: 1. see ?code examples? on page 8. 19.5.1 transmitter and receiver flags and interrupts the rxcn, txcn, and udren flag s and corresponding interrupt s in usart in mspim mode are identical in function to the normal usart operation. however, the receiver error status flags (fe, dor, and pe) are not in use and is always read as zero. 19.5.2 disabling the transmitter or receiver the disabling of the transmitter or receiver in usart in mspim mode is identical in function to the normal usart operation. 19.6 usart mspim r egister description the following section describes the registers used for spi operation using the usart. 19.6.1 usart mspim i/o data register - udrn the function and bit description of the usart data register (udrn) in mspi mode is identical to normal usart operation. see ?usart i/o data register n? udrn? on page 205. 19.6.2 usart mspim control and status register n a - ucsrna ? bit 7 - rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread dat a). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit will become zero. the rxcn flag can be used to generate a receive complete interr upt (see description of the rxcien bit). ? bit 6 - txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 - udren: usart data register empty the udren flag indicates if the transmit buff er (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrie bit). udren is set after a reset to indicate that the tr ansmitter is ready. ? bit 4:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrna is written. bit 765 4 3 2 1 0 rxcn txcn udren - - - - - ucsrna read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 1 1 0
220 7766f?avr?11/10 atmega16/32u4 19.6.3 usart mspim control and status register n b - ucsrnb ? bit 7 - rxcien: rx complete interrupt enable writing this bit to one enables interrupt on the rxcn flag. a usart rece ive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 - txcien: tx complete interrupt enable writing this bit to one enables interrupt on the txcn flag. a usart trans mit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 - udrie: usart data re gister empty interrupt enable writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrie bit is written to one, the glob al interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 - rxenn: receiver enable writing this bit to one enable s the usart receiver in mspim mode. the receiver will override normal port oper ation for the rxdn pin when enabled . disabling the receiver will flush the receive buffer. only enabling the receiver in mspi mode (i.e. setting rxenn=1 and txenn=0) has no meaning since it is the transmitter that controls the transfer clock and since only master mode is supported. ? bit 3 - txenn: transmitter enable writing this bit to one enables the usart tr ansmitter. the transmitter will override normal port operation for the txdn pin when enabled. the di sabling of the transmitter (writing txenn to zero) will not become effective until ongoing a nd pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrnb is written. 19.6.4 usart mspim control and status register n c - ucsrnc bit 7 6 5 4 3 2 1 0 rxcien txcien udrie rxenn txenn - - - ucsrnb read/write r/w r/w r/w r/w r/w r r r initial value 0 0 0 0 0 1 1 0 bit 76543210 umseln1 umseln0 - - - udordn ucphan ucpoln ucsrnc read/write r/w r/w r r r r/w r/w r/w initial value 0 0 0 0 0 1 1 0
221 7766f?avr?11/10 atmega16/32u4 ? bit 7:6 - umseln1:0: usart mode select these bits select the mode of operation of the usart as shown in table 19-3 . see ?usart control and status register n c ? ucsrnc? on page 207 for full description of the normal usart operation. the mspim is enabled when both umseln bits are set to one. the udordn, ucphan, and ucpoln can be set in t he same write operation where the mspim is enabled. ? bit 5:3 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrnc is written. ? bit 2 - udordn: data order when set to one the lsb of the data word is transmitted first. when set to zero the msb of the data word is transmitted first. refer to the frame formats section page 4 for details. ? bit 1 - ucphan: clock phase the ucphan bit setting determine if data is sampled on the leasing edge (first) or tailing (last) edge of xckn. refer to the spi data modes and timing section page 4 for details. ? bit 0 - ucpoln: clock polarity the ucpoln bit sets the polarity of the xc kn clock. the combination of the ucpoln and ucphan bit settings determine the timing of the data transfer. refer to the spi data modes and timing section page 4 for details. 19.6.5 usart mspim baud rate registers - ubrrnl and ubrrnh the function and bit description of the baud rate registers in mspi mode is identical to normal usart operation. see ?usart baud rate registers ? ubrrln and ubrrhn? on page 209. 19.7 avr usart mspim vs. avr spi the usart in mspim mode is fully co mpatible with the avr spi regarding: ? master mode timing diagram. ? the ucpoln bit functionality is identical to the spi cpol bit. ? the ucphan bit functionality is identical to the spi cpha bit. ? the udordn bit functionality is identical to the spi dord bit. however, since the usart in mspim mode reuses the usart resources, the use of the usart in mspim mode is somewhat different compared to the spi. in addition to differences of the control register bits, and that only master operation is supported by the usart in mspim mode, the following features differ between the two modules: table 19-3. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim)
222 7766f?avr?11/10 atmega16/32u4 ? the usart in mspim mode includes (double) buffering of the transmitter. the spi has no buffer. ? the usart in mspim mode receiver includes an additional buffer level. ? the spi wcol (write collis ion) bit is not included in usart in mspim mode. ? the spi double speed mode (spi2x) bit is not included. however, the same effect is achieved by setting ubrrn accordingly. ? interrupt timing is not compatible. ? pin control differs due to the master only operation of the usart in mspim mode. a comparison of the usart in mspim mode and the spi pins is shown in table 19-4 on page 222 . table 19-4. comparison of usart in mspim mode and spi pins. usart_mspim spi comment txdn mosi master out only rxdn miso master in only xckn sck (functionally identical) (n/a) ss not supported by usart in mspim
223 7766f?avr?11/10 atmega16/32u4 20. 2-wire serial interface 20.1 features ? simple yet powerful and flexible communication interface, only two bus lines needed ? both master and sla ve operation supported ? device can operate as transmitter or receiver ? 7-bit address space allows up to 128 different slave addresses ? multi-master arbitration support ? up to 400 khz data transfer speed ? slew-rate limited output drivers ? noise suppression circuitry rejects spikes on bus lines ? fully programmable slave address with general call support ? address recognition causes wake-up when avr is in sleep mode 20.2 2-wire serial in terface bus definition the 2-wire serial interface (twi) is ideally suit ed for typical microcon troller applications. the twi protocol allows the systems designer to in terconnect up to 128 diffe rent devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hard- ware needed to implement the bus is a single pull- up resistor for each of the twi bus lines. all devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the twi protocol. figure 20-1. twi bus interconnection 20.2.1 twi terminology the following definitions are frequently encountered in this section. device 1 device 2 device 3 device n sda scl ........ r1 r2 v cc table 20-1. twi terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock. slave the device addressed by a master. transmitter the device placing data on the bus. receiver the device reading data from the bus.
224 7766f?avr?11/10 atmega16/32u4 the power reduction twi bit, prtwi bit in ?power reduction register 0 - prr0? on page 46 must be written to zero to enable the 2-wire serial interface. 20.2.2 electrical interconnection as depicted in figure 20-1 , both bus lines are connected to the positive supply voltage through pull-up resistors. the bus drivers of all twi-compliant devices are open-drain or open-collector. this implements a wired-and functi on which is essential to the operation of the interface. a low level on a twi bus line is generated when one or more twi devices output a zero. a high level is output when all twi devices trim-state their outputs, allowing the pull-up resistors to pull the line high. note that all avr devices connected to the twi bus must be powered in order to allow any bus operation. the number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400 pf and the 7-bit slave address space. a detailed specification of the electrical char- acteristics of the twi is given in ?spi timing characteristics? on page 383 . two different sets of specifications are presented ther e, one relevant for bus speeds below 100 khz, and one valid for bus speeds up to 400 khz. 20.3 data transfer and frame format 20.3.1 transferring bits each data bit transferred on the twi bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generating start and stop conditions. figure 20-2. data validity 20.3.2 start and stop conditions the master initiates and terminates a data transmi ssion. the transmission is initiated when the master issues a start condition on the bus, and it is terminated when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should try to seize control of the bus. a special case occurs when a new start condition is issued between a start and stop condition. this is referred to as a repeated start condition, and is used when the master wis hes to initiate a new transfer without relin- quishing control of the bus. after a repeated start, the bus is considered busy until the next stop. this is identical to the start behavior, and therefore start is used to describe both start and repeated start for the remainder of this datasheet, unless otherwise noted. as sda scl data stable data stable data change
225 7766f?avr?11/10 atmega16/32u4 depicted below, start and stop conditions are signalled by changing the level of the sda line when the scl line is high. figure 20-3. start, repeated start and stop conditions 20.3.3 address packet format all address packets transmitted on the twi bus ar e 9 bits long, consisti ng of 7 address bits, one read/write control bit and an acknowledge bit. if the read/write bit is set, a read opera- tion is to be performed, otherwise a write operation should be performed. when a slave recognizes that it is being a ddressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycle. if the addressed slave is busy, or for some other reason can not service the mas- ter?s request, the sda line should be left high in the ack clock cycle. the master can then transmit a stop condition, or a repeated start condition to initiate a new transmission. an address packet consisting of a slave address and a read or a write bit is called sla+r or sla+w, respectively. the msb of the address byte is transmitted first. slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. when a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wi shes to transmit the same message to several slaves in the system. when the general call address followed by a write bit is transmitted on the bus, all slaves set up to ackn owledge the general call will pull th e sda line low in the ack cycle. the following data packets will then be received by all the slaves that acknowle dged the general call. note that transmitting the general call add ress followed by a read bit is meaningless, as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx should be reserved for future purposes. figure 20-4. address packet format sda scl start stop repeated start stop start sda scl start 12 789 addr msb addr lsb r/w ack
226 7766f?avr?11/10 atmega16/32u4 20.3.4 data packet format all data packets transmitted on the twi bus are nine bits long, consisting of one data byte and an acknowledge bit. during a data transfer, the master generates the clock and the start and stop conditions, while the receiver is res ponsible for acknowledging the reception. an acknowledge (ack) is signalled by the receiver pulling the sda line low during the ninth scl cycle. if the receiver leaves the sda line high, a nack is signalled. when the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a nack after the final byte. the msb of the data byte is transmitted first. figure 20-5. data packet format 20.3.5 combining address and data packets into a transmission a transmission basically consists of a start co ndition, a sla+r/w, one or more data packets and a stop condition. an empty message, consisting of a start followed by a stop condi- tion, is illegal. note that the wired-an ding of the scl line can be used to implement handshaking between the master and the slave. the slave can extend the scl low period by pulling the scl line low. this is useful if the cloc k speed set up by the master is too fast for the slave, or the slave needs extra time for proces sing between the data transmissions. the slave extending the scl low period will not affect t he scl high period, which is determined by the master. as a consequence, the slave can reduce the twi data transfer speed by prolonging the scl duty cycle. figure 20-6 shows a typical data transmission. note that several data bytes can be transmitted between the sla+r/w and the stop condition, depending on the software protocol imple- mented by the application software. figure 20-6. typical data transmission 12 789 data msb data lsb ack aggregate sda sda from transmitter sda from receiver scl from master sla+r/w data byte stop, repeated start or next data byte 12 789 data byte data msb data lsb ack sda scl start 12 789 addr msb addr lsb r/w ack sla+r/w stop
227 7766f?avr?11/10 atmega16/32u4 20.4 multi-master bus systems, arbitration and synchronization the twi protocol allows bus systems with seve ral masters. special concerns have been taken in order to ensure that transmis sions will proceed as normal, even if two or more masters initiate a transmission at the same time. two problems arise in multi-master systems: ? an algorithm must be implemented allowing only one of the masters to complete the transmission. all other masters should cease transmission when they discover that they have lost the selection process. this selection proc ess is called arbitration. when a contending master discovers that it has lost the arbitration process, it should immediately switch to slave mode to check whether it is being addressed by the winning master. the fact that multiple masters have started transmission at the same time should not be detectable to the slaves, i.e. the data being transferred on the bus must not be corrupted. ? different masters may use different scl frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. this will fac ilitate the arbitration process. the wired-anding of the bus lines is used to solv e both these problems. the serial clocks from all masters will be wired-anded, yielding a co mbined clock with a high period equal to the one from the master with the shortest high period. the low period of the combined clock is equal to the low period of the master with the longest low period. note that all masters listen to the scl line, effectively starting to count their scl high and low time-out periods when the combined scl line goes high or low, respectively. figure 20-7. scl synchronization betw een multiple masters arbitration is carried out by all masters cont inuously monitoring the sda line after outputting data. if the value read from the sda line does not match the value the master had output, it has lost the arbitration. note that a master can only lose arbitration when it outputs a high sda value while another master outputs a low value. the losing master should immediately go to slave mode, checking if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. arbitration will cont inue until only one master re mains, and this may take many ta low ta high scl from master a scl from master b scl bus line tb low tb high masters start counting low period masters start counting high period
228 7766f?avr?11/10 atmega16/32u4 bits. if several masters are trying to address th e same slave, arbitratio n will continue into the data packet. figure 20-8. arbitration between two masters note that arbitration is not allowed between: ? a repeated start cond ition and a data bit. ? a stop condition and a data bit. ? a repeated start and a stop condition. it is the user software?s responsibility to ensur e that these illegal arbitration conditions never occur. this implies that in multi-master systems, all data transfers must use the same composi- tion of sla+r/w and data packets. in other words: all transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined. 20.5 overview of the twi module the twi module is comprised of several submodules, as shown in figure 20-9 . all registers drawn in a thick line are accessible through the avr data bus. sda from master a sda from master b sda line synchronized scl line start master a loses arbitration, sda a sda
229 7766f?avr?11/10 atmega16/32u4 figure 20-9. overview of the twi module 20.5.1 scl and sda pins these pins interface the avr twi with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the twi specification. the input stages contain a spike suppression unit removing spikes shorter than 50 ns. note that the internal pull-ups in the avr pads can be enabled by setting the port bits corresponding to the scl and sda pins, as explained in the i/o port section. the internal pull-ups can in some systems eliminate the need for external ones. 20.5.2 bit rate generator unit this unit controls the period of scl when oper ating in a master mode. the scl period is con- trolled by settings in the twi bit rate register (twbr) and the prescaler bits in the twi status register (twsr). slave operation does not depend on bit rate or prescaler settings, but the cpu clock frequency in the slave must be at l east 16 times higher than the scl frequency. note that slaves may prolong the scl low period, thereby reducing the average twi bus clock period. the scl frequency is generated according to the following equation: twi unit address register (twar) address match unit address comparator control unit control register (twcr) status register (twsr) state machine and status control scl slew-rate control spike filter sda slew-rate control spike filter bit rate generator bit rate register (twbr) prescaler bus interface unit start / stop control arbitration detection ack spike suppression address/data shift register (twdr)
230 7766f?avr?11/10 atmega16/32u4 ? twbr = value of the twi bit rate register. ? twps = value of the prescaler bits in the twi status register. note: twbr should be 10 or higher if the twi operates in master mode. if twbr is lower than 10, the master may produce an incorrect output on sda and scl for the reminder of the byte. the prob- lem occurs when operating the twi in master mode, sending start + sla + r/w to a slave (a slave does not need to be connected to the bus for the condition to happen). 20.5.3 bus interface unit this unit contains the data and address shif t register (twdr), a start/stop controller and arbitration detection hardware. the twdr contains the address or data bytes to be transmitted, or the address or data bytes received. in addition to the 8-bit twdr, the bus interface unit also contains a register containing the (n)ack bit to be transmitted or receiv ed. this (n)ack regis- ter is not directly accessible by the application software. however, when re ceiving, it can be set or cleared by manipulating the twi control r egister (twcr). when in transmitter mode, the value of the received (n)ack bit can be determined by the value in the twsr. the start/stop controller is responsible for gene ration and detection of start, repeated start, and stop conditions. the start/stop controller is able to detect start and stop conditions even when the avr mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the twi has initiated a transmission as master, the arbitration detection hardware continu- ously monitors the transmission trying to determine if arbitration is in process. if the twi has lost an arbitration, the control unit is informed. correct action can then be taken and appropriate status codes generated. 20.5.4 address match unit the address match unit checks if received address bytes match the seven-bit address in the twi address register (twar). if the twi general call recognition enable (twgce) bit in the twar is written to one, all incoming address bits will also be compared against the general call address. upon an address match, the control unit is informed, allowing correct action to be taken. the twi may or may not acknowledge it s address, depending on settings in the twcr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake up if addressed by a master. if another interrupt (e.g., int0) occurs during twi power-down address match and wakes up the cpu, the twi aborts opera- tion and return to it?s idle state. if this cause any problems, ensure that twi address match is the only enabled interrupt when entering power-down. 20.5.5 control unit the control unit monitors the twi bus and generates responses corresponding to settings in the twi control register (twcr). when an event requiring the attention of the application occurs on the twi bus, the twi interrupt flag (twint) is asserted. in the next clock cycle, the twi sta- tus register (twsr) is updated with a stat us code identifying the event. the twsr only contains relevant status information when the tw i interrupt flag is asserted. at all other times, the twsr contains a special stat us code indicating that no relevant status information is avail- able. as long as the twint flag is set, the scl line is held low. this allows the application software to complete its tasks before allowing the twi transmission to continue. scl frequency cpu clock frequency 16 2(twbr) 4 twps ? + ----------------------------------------------------------- =
231 7766f?avr?11/10 atmega16/32u4 the twint flag is set in the following situations: ? after the twi has transmitted a start/repeated start condition. ? after the twi has transmitted sla+r/w. ? after the twi has transmitted an address byte. ? after the twi has lost arbitration. ? after the twi has been addressed by own slave address or general call. ? after the twi has received a data byte. ? after a stop or repeated start has been received while still addressed as a slave. ? when a bus error has occurred due to an illegal start or stop condition. 20.6 twi register description 20.6.1 twi bit rate register ? twbr ? bits 7..0 ? twi bit rate register twbr selects the division factor for the bit rate generator. the bit rate generator is a frequency divider which generates the scl clock frequency in the master modes. see ?bit rate generator unit? on page 229 for calculating bit rates. 20.6.2 twi control register ? twcr the twcr is used to control the operation of the twi. it is used to enable the twi, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the twdr. it also indicates a write collision if data is attempted written to twdr while the regist er is inaccessible. ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the twi has finished its current job and expects application software response. if the i-bit in sreg and twie in twcr are set, the mcu will jump to the twi interrupt vector. while the twint flag is set, the scl low period is stretched. the twint flag must be cleared by software by writing a logic one to it. note that this flag is not automati- cally cleared by hardware when executing the interr upt routine. also note that clearing this flag starts the operation of the twi, so all accesses to the twi address register (twar), twi sta- tus register (twsr), and twi data register (twdr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the twea bit controls the generation of the acknowledge pulse. if the twea bit is written to one, the ack pulse is generated on the twi bus if the following conditions are met: bit 76543210 twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value00000000
232 7766f?avr?11/10 atmega16/32u4 1. the device?s own slave address has been received. 2. a general call has been received, while the twgce bit in the twar is set. 3. a data byte has been received in master receiver or slave receiver mode. by writing the twea bit to zero, the device can be virtually disconnected from the 2-wire serial bus temporarily. address re cognition can then be resumed by writing the twea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the twsta bit to one when it desires to become a master on the 2-wire serial bus. the twi hardware checks if the bu s is available, and generates a start condition on the bus if it is free. however, if the bus is not free, the twi waits until a stop condition is detected, and then generates a new start condition to claim the bus master status. twsta must be cleared by software when the start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit writing the twsto bit to one in master mode will g enerate a stop cond ition on the 2-wire serial bus. when the stop condition is exec uted on the bus, the twsto bit is cleared auto- matically. in slave mode, setting the twsto bit can be used to recover from an error condition. this will not generate a stop co ndition, but the twi returns to a well-defined unaddressed slave mode and releases the scl and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the twwc bit is set when attempting to write to the twi data register ? twdr when twint is low. this flag is cleared by writing the twdr register when twint is high. ? bit 2 ? twen: twi enable bit the twen bit enables twi operation and activate s the twi interface. when twen is written to one, the twi takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filters. if this bit is written to zero, the twi is switched off and all twi transmissions are terminated, regardless of any ongoing operation. ? bit 1 ? res: reserved bit this bit is a reserved bit an d will always read as zero. ? bit 0 ? twie: twi interrupt enable when this bit is written to one, and the i-bit in sreg is set, th e twi interrupt request will be acti- vated for as long as the twint flag is high. 20.6.3 twi status register ? twsr ? bits 7..3 ? tws: twi status these 5 bits reflect the status of the twi logic and the 2-wire serial bus. the different status codes are described later in this section. note that the value read from twsr contains both the 5-bit status value and the 2-bit prescaler value. the application designer should mask the pres- bit 76543210 tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/writerrrrrrr/wr/w initial value11111000
233 7766f?avr?11/10 atmega16/32u4 caler bits to zero when checking the status bits. this makes status checking independent of prescaler setting. this approach is used in this datasheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1..0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. to calculate bit rates, see ?bit rate generator unit? on page 229 . the value of twps1..0 is used in the equation. 20.6.4 twi data register ? twdr in transmit mode, twdr contains the next byte to be transmitted. in receive mode, the twdr contains the last byte received. it is writable while the twi is not in the process of shifting a byte. this occurs when the twi interrupt flag (twint) is set by hardware. note that the data regis- ter cannot be initialized by the user before the first interrupt occurs. the data in twdr remains stable as long as twint is se t. while data is shifted out, data on the bus is simultaneously shifted in. twdr always contains the last byte present on the bus, except after a wake up from a sleep mode by the twi interrupt. in this case, the contents of twdr is undefined. in the case of a lost bus arbitration, no data is lost in the transition from master to slave. handling of the ack bit is controlled automatically by the twi logic, the cpu cannot access the ack bit directly. ? bits 7..0 ? twd: twi data register these eight bits constitute the next data byte to be transmitted, or the latest data byte received on the 2-wire serial bus. 20.6.5 twi (slave) address register ? twar the twar should be loaded with the 7-bit slave address (in the seven most significant bits of twar) to which the twi will respond when programmed as a slave transmitter or receiver, and not needed in the master modes. in multi master systems, twar must be set in masters which can be addressed as slaves by other masters. table 20-2. twi bit rate prescaler twps1 twps0 prescaler value 001 014 1016 1164 bit 76543210 twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111111 bit 76543210 twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111110
234 7766f?avr?11/10 atmega16/32u4 the lsb of twar is used to enable recognition of the general call address (0x00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a match is found, an interrupt request is generated. ? bits 7..1 ? twa: twi (slave) address register these seven bits constitute th e slave address of the twi unit. ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the 2-wire serial bus. 20.6.6 twi (slave) address mask register ? twamr ? bits 7..1 ? twam: twi address mask the twamr can be loaded with a 7-bit slave addr ess mask. each of the bits in twamr can mask (disable) the corresponding address bit in the twi address register (twar). if the mask bit is set to one then the address match l ogic ignores the compare between the incoming address bit and the corresponding bit in twar. figure 20-10 shows the address match logic in detail. figure 20-10. twi address match logic, block diagram ? bit 0 ? res: reserved bit this bit is reserved and will always read as zero. 20.7 using the twi the avr twi is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmission of a start condition. because the twi is interrupt-based, the application software is free to carry on other operations during a twi byte transfer. note that the twi interrupt enable (twie) bit in twcr to gether with the global interrupt enable bit in sreg allow the application to decide whether or not assertion of the twint flag should gener- ate an interrupt request. if the twie bit is clear ed, the application must poll the twint flag in order to detect actions on the twi bus. when the twint flag is asserted, the twi has finished an operation and awaits application response. in this case, the twi status register (twsr) contains a value indicating the current bit 76543210 twam[6:0] ? twamr read/write r/w r/w r/w r/w r/w r/w r/w r initial value00000000 address match address bit comparator 0 address bit comparator 6..1 twar0 twamr0 address bit 0
235 7766f?avr?11/10 atmega16/32u4 state of the twi bus. the application software can then decide how the twi should behave in the next twi bus cycle by manipulating the twcr and twdr registers. figure 20-11 is a simple example of how the application can interface to the twi hardware. in this example, a master wishes to transmit a single data byte to a slave. this description is quite abstract, a more detailed explanation follows later in this section. a simple code example imple- menting the desired behavior is also presented. figure 20-11. interfacing the application to the twi in a typical transmission 1. the first step in a twi transmission is to transmit a start condition. this is done by writing a specific value into twcr, instructing the twi hardware to transmit a start condition. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the tw int bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmission of the start condition. 2. when the start condition has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the start condition has success- fully been sent. 3. the application software should now examine the value of twsr, to make sure that the start condition was successfully transmitted. if twsr indicates otherwise, the appli- cation software might take some special acti on, like calling an error routine. assuming that the status code is as expected, the application must load sla+w into twdr. remember that twdr is used both for address and data. after twdr has been loaded with the desired sla+w, a specific value must be written to twcr, instructing the twi hardware to transmit the sla+w present in twdr. which value to write is described later on. however, it is important t hat the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmis sion of the address packet. 4. when the address packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the address packet has success- fully been sent. the status code will also reflect whether a slave acknowledged the packet or not. start sla+w a data a stop 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla+w sent, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla+w into twdr, and loads appropriate control signals into twcr, makin sure that twint is written to one, and twsta is written to zero. 5. check twsr to see if sla+w was sent and ack received. application loads data into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, making sure that twint is written to one twi bus indicates twint set application action twi hardware action
236 7766f?avr?11/10 atmega16/32u4 5. the application software should now examine the value of twsr, to make sure that the address packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some spe- cial action, like calling an error routine. assu ming that the status code is as expected, the application must load a data packet into twdr. subsequently, a specific value must be written to twcr, instructing the twi hardware to transmit the data packet present in twdr. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immedi- ately after the application has cleared twin t, the twi will initiate transmission of the data packet. 6. when the data packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the data packet has successfully been sent. the status code will also reflec t whether a slave acknowledged the packet or not. 7. the application software should now examine the value of twsr, to make sure that the data packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some spe- cial action, like calling an error routine. assu ming that the status code is as expected, the application must write a specific valu e to twcr, instructing the twi hardware to transmit a stop condition. which value to wr ite is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the applicat ion has cleared twint, the twi will initiate transmission of the stop condition. note that twint is not set after a stop condition has been sent. even though this example is simple, it shows t he principles involved in all twi transmissions. these can be summarized as follows: ? when the twi has finished an operation and expects application response, the twint flag is set. the scl line is pull ed low until twint is cleared. ? when the twint flag is set, the user must update all twi registers with the value relevant for the next twi bus cycle. as an example, twdr must be loaded with the value to be transmitted in the next bus cycle. ? after all twi register updates and other pending application software tasks have been completed, twcr is written. when writing tw cr, the twint bit should be set. writing a one to twint clears the flag. the twi will then commence executing whatever operation was specified by the twcr setting. in the following an assembly and c implementation of the example is given. note that the code below assumes that several definitions have been made, for example by using include-files.
237 7766f?avr?11/10 atmega16/32u4 assembly code example c example comments 1 ldi r16, (1< 238 7766f?avr?11/10 atmega16/32u4 20.8 transmission modes the twi can operate in one of four major modes. these are named master transmitter (mt), master receiver (mr), slave transmitter (st) and slave receiver (sr). several of these modes can be used in the same application. as an example, the twi can use mt mode to write data into a twi eeprom, mr mode to read the data back from the eeprom. if other masters are present in the system, some of these might transmit data to the twi, and then sr mode would be used. it is the application softw are that decides which modes are legal. the following sections describe each of these modes. possible status codes are described along with figures detailing data transmission in each of the modes. these figures contain the following abbreviations: s: start condition rs: repeated start condition r: read bit (high level at sda) w: write bit (low level at sda) a: acknowledge bit (low level at sda) a : not acknowledge bit (high level at sda) data: 8-bit data byte p: stop condition sla: slave address in figure 20-13 to figure 20-19 , circles are used to indicate that the twint flag is set. the numbers in the circles show the status code held in twsr, with the prescaler bits masked to zero. at these points, actions must be taken by the application to continue or complete the twi transfer. the twi transfer is suspended until the twint flag is cleared by software. when the twint flag is set, the status code in twsr is used to determine the appropriate soft- ware action. for each status code, the required software action and details of the following serial transfer are given in table 20-3 to table 20-6 . note that the prescaler bits are masked to zero in these tables. 20.8.1 master transmitter mode in the master transmitter mode, a number of data bytes are transmitted to a slave receiver (see figure 20-12 ). in order to enter a master mode, a start condition must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is trans- mitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero.
239 7766f?avr?11/10 atmega16/32u4 figure 20-12. data transfer in master transmitter mode a start condition is sent by wr iting the following value to twcr: twen must be set to enable the 2-wire serial interface, twsta must be written to one to trans- mit a start condition and twint must be written to one to cl ear the twint flag. the twi will then test the 2-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hardware, and the status code in twsr will be 0x08 (see table 20-3 ). in order to enter mt mode, sla+w must be transmitted. this is done by writing sla+w to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the tr ansfer. this is accomplis hed by writing the follow- ing value to twcr: when sla+w have been transmitted and an acknowledgement bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x18, 0x20, or 0x38. the appropriate action to be taken for each of these status codes is detailed in table 20-3 . when sla+w has been successfully transmitted, a data packet should be transmitted. this is done by writing the data byte to twdr. twdr must only be written when twint is high. if not, the access will be discarded, and the write collision bit (twwc) will be set in the twcr regis- ter. after updating twdr, the twint bit should be cleared (by writing it to one) to continue the transfer. this is acco mplished by writing the following value to twcr: this scheme is repeated until the last byte has been sent and the transfer is ended by generat- ing a stop condition or a repeated start condition. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master transmitter device 2 slave receiver device 3 device n sda scl ........ r1 r2 v cc
240 7766f?avr?11/10 atmega16/32u4 after a repeated start condition (state 0x10) th e 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode with- out losing control of the bus. table 20-3. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a 0x08 a start condition has been transmitted load sla+w 0 0 1 x sla+w will be transmitted; ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+w or load sla+r 0 0 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode 0x18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x28 data byte has been transmit- ted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x30 data byte has been transmit- ted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode entered a start condition will be transmitted when the bus becomes free
241 7766f?avr?11/10 atmega16/32u4 figure 20-13. formats and states in the master transmitter mode 20.8.2 master receiver mode in the master receiver mode, a number of data bytes are received from a slave transmitter (slave see figure 20-14 ). in order to enter a master mode, a start condition must be transmit- ted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the stat us codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. s sla w a data a p $08 $18 $28 r sla w $10 ap $20 p $30 a or a $38 a other master continues a or a $38 other master continues r a $68 other master continues $78 $b0 to corresponding states in slave mode mt mr successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero s
242 7766f?avr?11/10 atmega16/32u4 figure 20-14. data transfer in ma ster receiver mode a start condition is sent by wr iting the following value to twcr: twen must be written to one to enable the 2-wire serial interface, twsta must be written to one to transmit a start condition and twint must be set to clear the twint flag. the twi will then test the 2-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hard- ware, and the status code in twsr will be 0x08 (see table 20-3 ). in order to enter mr mode, sla+r must be transmitted. this is done by wr iting sla+r to twdr. th ereafter the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: when sla+r have been transmitted and an acknowledgement bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x38, 0x40, or 0x48. the appropriate action to be taken for each of these status codes is detailed in table 20-4 . received data can be read from the twdr register when the twint flag is set high by hardware. this scheme is repeated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a nack after the last received data byte. the transfer is ended by generating a stop condition or a repeated start condition. a stop condition is genera ted by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) th e 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master receiver device 2 slave transmitter device 3 device n sda scl ........ r1 r2 v cc
243 7766f?avr?11/10 atmega16/32u4 the master to switch between slaves, master transmitter mode and master receiver mode with- out losing control over the bus. table 20-4. status codes for master receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a 0x08 a start condition has been transmitted load sla+r 0 0 1 x sla+r will be transmitted ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+r or load sla+w 0 0 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode 0x38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free 0x40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset
244 7766f?avr?11/10 atmega16/32u4 figure 20-15. formats and states in the master receiver mode 20.8.3 slave receiver mode in the slave receiver mode, a number of data bytes are received from a master transmitter (see figure 20-16 ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 20-16. data transfer in slave receiver mode to initiate the slave receiver mode, twar and twcr must be initialized as follows: s sla r a data a $08 $40 $50 sla r $10 ap $48 a or a $38 other master continues $38 other master continues w a $68 other master continues $78 $b0 to corresponding states in slave mode mr mt successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p data a $58 a r s twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address device 3 device n sda scl ........ r1 r2 v cc device 2 master transmitter device 1 slave receiver
245 7766f?avr?11/10 atmega16/32u4 the upper 7 bits are the address to which the 2-wire serial interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the twi will operate in sr mode, otherwise st mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 20-5 . the slave receiver mode may also be entered if arbitration is lost while the twi is in the master mode (see states 0x68 and 0x78). if the twea bit is reset during a transfer, the tw i will return a ?not acknowledge? (?1?) to sda after the next received data byte. this can be used to indicate that the slave is not able to receive any more bytes. while twea is zero, the twi does not acknowledge its own slave address. however, the 2-wire se rial bus is still monitored and address recognit ion may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the 2-wire serial bus clock as a clock sour ce. the part will then wake up from sleep and the twi will hold the scl clock low during the wake up and until the twin t flag is cleared (by writing it to one). further data reception will be carried out as normal, with the avr clocks run- ning as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the 2-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
246 7766f?avr?11/10 atmega16/32u4 table 20-5. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hard- ware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a 0x60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0x90 previously addressed with general call; data has been re- ceived; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xa0 a stop condition or repeated start condition has been received while still addressed as slave no action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
247 7766f?avr?11/10 atmega16/32u4 figure 20-17. formats and states in the slave receiver mode 20.8.4 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure 20-18 ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 20-18. data transfer in slave transmitter mode s sla w a data a $60 $80 $88 a $68 reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave reception of the general call address and one or more data bytes last data byte received is not acknowledged n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data a $80 $a0 p or s a adataa $70 $90 $98 a $78 p or s data a $90 $a0 p or s a general call arbitration lost as master and addressed as slave by general call data a device 3 device n sda scl ........ r1 r2 v cc device 2 master receiver device 1 slave transmitter
248 7766f?avr?11/10 atmega16/32u4 to initiate the slave transmitter mode, twar and twcr must be in itialized as follows: the upper seven bits are the address to which the 2-wire serial interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the twi will operate in st mode, otherw ise sr mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 20-6 . the slave transmitter mode may also be entered if arbitration is lost while the twi is in the master mode (see state 0xb0). if the twea bit is written to zero during a transfer, the twi will transm it the last byte of the trans- fer. state 0xc0 or state 0xc8 will be entere d, depending on whether the master receiver transmits a nack or ack after the final byte. the twi is switched to the not addressed slave mode, and will ignore the mast er if it continues th e transfer. thus the ma ster receiver receives all ?1? as serial data. state 0xc8 is entered if the master demands additional data bytes (by transmitting ack), even though the slave has transmitted the last byte (twea zero and expect- ing nack from the master). while twea is zero, the twi does not respond to its own slave address. however, the 2-wire serial bus is still monitored an d address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the 2-wire serial bus clock as a clock sour ce. the part will then wake up from sleep and the twi will hold the scl clock will low during th e wake up and until the twint flag is cleared (by writing it to one). further data tr ansmission will be carried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the 2-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
249 7766f?avr?11/10 atmega16/32u4 table 20-6. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hard- ware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a 0xa8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xc0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xc8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
250 7766f?avr?11/10 atmega16/32u4 figure 20-19. formats and states in the slave transmitter mode 20.8.5 miscellaneous states there are two status codes that do not correspond to a defined twi state, see table 20-7 . status 0xf8 indicates that no relevant inform ation is available because the twint flag is not set. this occurs between other states, and when the twi is not involved in a serial transfer. status 0x00 indicates that a bus error has occu rred during a 2-wire serial bus transfer. a bus error occurs when a start or stop condition occurs at an illegal position in the format frame. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. when a bus error occurs, twint is set. to recover from a bus error, the twsto flag must set and twint must be cleared by writing a logic one to it. this causes the twi to enter the not addressed slave mode and to clear the twsto flag (no other bits in twcr are affected). the sda and scl lines are released, and no stop condition is transmitted. 20.8.6 combining several twi modes in some cases, several twi modes must be combined in order to complete the desired action. consider for example reading data from a serial eeprom. typically, such a transfer involves the following steps: 1. the transfer must be initiated. 2. the eeprom must be instructed what location should be read. 3. the reading must be performed. 4. the transfer must be finished. s sla r a data a $a8 $b8 a $b0 reception of the own slave address and one or more data bytes last data byte transmitted. switched to not addressed slave (twea = '0') arbitration lost as master and addressed as slave n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data $c0 data a a $c8 p or s all 1's a table 20-7. miscellaneous states status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a 0xf8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer 0x00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condi- tion is sent on the bus. in all cases, the bus is released and twsto is cleared.
251 7766f?avr?11/10 atmega16/32u4 note that data is transmitted both from master to slave and vice versa. the master must instruct the slave what location it wants to read, r equiring the use of the mt mode. subsequently, data must be read from the slave, implying the use of the mr mode. thus, the transfer direction must be changed. the master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation. if this principle is violated in a multi master sys- tem, another master can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data lo cation. such a change in transfe r direction is accomplished by transmitting a repeated start between the trans mission of the address byte and reception of the data. after a repeated start, the master keeps ownership of the bus. the following figure shows the flow in this transfer. figure 20-20. combining several twi modes to access a serial eeprom 20.9 multi-master syst ems and arbitration if multiple masters are connected to the same bus, transmissions may be initiated simultane- ously by one or more of them. the twi standar d ensures that such situations are handled in such a way that one of the mast ers will be allowed to proceed wit h the transfer, and that no data will be lost in the process. an example of an ar bitration situation is depicted below, where two masters are trying to transmit data to a slave receiver. figure 20-21. an arbitration example several different scenarios may arise during arbitration, as described below: ? two or more masters are performing identical communication with the same slave. in this case, neither the slave nor any of the masters will know about the bus contention. ? two or more masters are accessing the same slave with different data or direction bit. in this case, arbitration will occur, either in the read /write bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. losing masters will switch to not addressed slave mode or wa it until the bus is free and transmit a new start condition, depending on application software action. master transmitter master receiver s = start rs = repeated start p = stop transmitted from master to slave transmitted from slave to master s sla+w a address a rs sla+r a data a p device 1 master transmitter device 2 master transmitter device 3 slave receiver device n sda scl ........ r1 r2 v cc
252 7766f?avr?11/10 atmega16/32u4 ? two or more masters are access ing different slaves. in this ca se, arbitration will occur in the sla bits. masters trying to ou tput a one on sda while another mast er outputs a zero will lose the arbitration. masters losing arbitration in sla will switch to slave mode to check if they are being addressed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/write bit. if they are not being addressed, they will switch to not addressed slave mode or wait until the bus is free and transmit a new start condition, depending on application software action. this is summarized in figure 20-22 . possible status values are given in circles. figure 20-22. possible status codes caused by arbitration own address / general call received arbitration lost in sla twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free no arbitration lost in data direction ye s write data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received read b0 68/78 38 sla start data stop
253 7766f?avr?11/10 atmega16/32u4 21. usb controller 21.1 features ? supports full-speed and low-speed device role ? complies with usb specification v2.0 ? supports ping-pong mode (dual bank) ? 832 bytes of dpram: ? 1 endpoint 64 bytes max (default control endpoint) ? 1 endpoints of 256 bytes max, (one or two banks) ? 5 endpoints of 64 bytes max, (one or two banks) ? crystal-less operation for low-speed mode 21.2 block diagram the usb controller provides the hardware to interface a usb link to a data flow stored in a dou- ble port memory (dpram). the usb controller requires a 48 mhz 0.25% reference clock (for full-speed operation), which is the output of an internal pll. the on-chip pll generates the internal high frequency (48 mhz) clock for usb interface. the pll clock input can be configured to use external low-power crystal oscillator, external sour ce clock or internal rc (see sectio n ?crystal-less operation?, page 256). the 48mhz clock is used to generate a 12 mhz full-speed (or 1.5 mhz low-speed) bit clock from the received usb differential data and to transmit data according to full or low speed usb device tolerance. clock recovery is done by a digital phase locked loop (dpll) block, which is compliant with the jitter specification of the usb bus. to comply with the usb electric al specification, usb buffers (d+ or d-) should be powered within the 3.0 to 3.6v range. as atmega16u4/atmega32u4 can be powered up to 5.5v, an internal regulator provides the usb buffers power supply. figure 21-1. usb controller blo ck diagram overview cpu usb regulator usb interface pll clk 8mhz clk 48mhz pll clock prescaler on-chip usb dpram dpll clock recovery ucap d- d+ vbus uvcc avcc div-by-2 & xt1 clock mux intrc
254 7766f?avr?11/10 atmega16/32u4 21.3 typical applica tion implementation depending on the target application power supply, the atmega16u4/atmega32u4 requires dif- ferent hardware typical implementations. figure 21-2. operating modes versus frequency and power-supply 21.3.1 bus powered device figure 21-3. typical bus powered application with 5v i/o vcc (v) vcc min 0 3.0 3.4 5.5 usb not operational usb compliant, without internal regulator usb compliant, with internal regulator 4.5 2.7 max operating frequency (mhz) 8 mhz 16 mhz 2 mhz 3.6 1f udp udm vbus uvss uid ucap d- d+ vbus uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd rs=22 rs=22
255 7766f?avr?11/10 atmega16/32u4 figure 21-4. typical bus powered application with 3v i/o 21.3.2 self powered device figure 21-5. typical self powered application with 3.4v to 5.5v i/o 1f uvss external 3v regulator udp udm vbus uvss uid ucap d- d+ vbus uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd rs=22 rs=22 1f external 3.4v - 5.5v power supply udp udm vbus uvss uid ucap d- d+ vbus uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd rs=22 rs=22
256 7766f?avr?11/10 atmega16/32u4 figure 21-6. typical self powered application with 3.0v to 3.6 i/o 21.4 crystal-less operation to reduce external components count and bom cost, the usb module can be configured to operate in low-speed mode with internal rc oscill ator as input source clock for the pll. the internal rc oscillator is factory calibrated to satisfy the usb low speed frequency accuracy within the 0c and -40c temperature range. for usb full-speed operation only external crystal oscillator or external source clock can be used. 21.5 design guidelines ? serial resistors on usb data lin es must have 22 ohms value ( +/- 5%). ? traces from the input usb receptable (or from the cable connection in the case of a tethered device) to the usb microcontroller pads should be as short as possible, and follow differential traces routing rules (same length, as nea r as possible, avoid via accumulation). ? voltage transient / esd suppressors may also be used to prevent usb pads to be damaged by external disturbances. ?u cap capacitor should be 1f ( +/- 10%) for correct operation. ? a 10f capacitor is highly recommended on vbus line 1f external 3.0v - 3.6v power supply udp udm vbus uvss uid ucap d- d+ vbus uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd rs=22 rs=22
257 7766f?avr?11/10 atmega16/32u4 21.6 general operating modes 21.6.1 introduction the usb controller is disabled and reset after an hardware reset generated by: ? power on reset ? external reset ? watchdog reset ? brown out reset ? jtag reset but another available and optional cpu reset source is: ? usb end of reset in this case, the usb controller is reset, but not disabled (so that the device remains attached). 21.6.2 power-on and reset the next diagram explains the usb controller main states on power-on: figure 21-7. usb controller states after reset usb controller state after an hardware reset is ?reset?. in this state: ? usbe is not set ? the usb controller clock is stopped in order to minimize the power consumption (frzclk=1), ? the usb controller is disabled, ? the usb pad is in the suspend mode, ? the device usb controller internal state is reset. after setting usbe, the usb controller enters the device state. the controller is ?idle?. the usb controller can at any time be stopped by clearing usbe. in fact, clearing usbe acts as an hardware reset. 21.6.3 interrupts two interrupts vectors are assigned to usb interface. device r eset usbe=0 < any other state> usbe=1 c lock stopped frzclk=1 m acro off usbe=0 usbe=0 hw reset
258 7766f?avr?11/10 atmega16/32u4 figure 21-8. usb interrupt system the usb hardware module distinguishes between usb general events and usb endpoint events that are relevant with data transfers relative to each endpoint. figure 21-9. usb general interrupt vector sources almost all these interrupts are time-relative event s that will be detected only if the usb clock is enabled (frzclk bit set), except for: ? vbus plug-in detection (insert, remove) ? wakeup interrupt that will trigger each time a state change is detecte d on the data lines. this asynchronous interrupts allow to wake-up a device that is in power-down mode, generally after that the usb has entered the suspend state. usb general interrupt usb device interrupt usb general interrupt vector endpoint interrupt usb endpoint/pipe interrupt vector vbusti usbint.0 vbuste usbcon.0 usb general interrupt vector uprsmi udint.6 uprsme udien.6 eorsmi udint.5 eorsme udien.5 wakeupi udint.4 wakeupe udien.4 eorsti udint.3 eorste udien.3 sofi udint.2 sofe udien.2 suspi udint.0 suspe udien.0 usb device interrupt usb general interrupt vector asynchronous interrupt source (allows the cpu to wake up from power down mode)
259 7766f?avr?11/10 atmega16/32u4 figure 21-10. usb endpoint interrupt vector sources each endpoint has 8 interrupts sources associat ed with flags, and each source can be enabled or not to trigger the corresponding endpoint inte rrupt. if, for an endpoint, at least one of the sources is enabled to trigger interrupt, the correspo nding event(s) will make the program branch to the usb endpoint interrupt vector. the user ma y determine the source (endpoint) of the inter- rupt by reading the ueint register, and then handle the event detected by polling the different flags. 21.7 power modes 21.7.1 idle mode in this mode, the cpu core is halted (cpu clock stopped). the idle mode is taken wether the usb controller is running or not. the cpu ?wakes up? on any usb interrupts. 21.7.2 power down in this mode, the oscillator is stopped and halts all the clocks (cpu and peripherals). the usb controller ?wakes up? when: ? the wakeupi interrupt is triggered ? the vbusti interrupt is triggered flerre ueienx.7 overfi uestax.6 underfi uestax.5 nakini ueintx.6 nakine ueienx.6 nakouti ueintx.4 txstpe ueienx.4 rxstpi ueintx.3 rxstpe ueienx.3 rxouti ueintx.2 rxoute ueienx.2 stalledi ueintx.1 stallede ueienx.1 epint ueint.x endpoint 0 endpoint 1 endpoint 2 endpoint 3 endpoint 4 endpoint 5 txini ueintx.0 txine ueienx.0 usb endpoint interrupt vector endpoint 6
260 7766f?avr?11/10 atmega16/32u4 21.7.3 freeze clock the firmware has the ability to reduce the power consumption by setting the frzclk bit, which freeze the clock of usb controller. when frzclk is set, it is still possible to access to the fol- lowing registers: ? usbcon, usbsta, usbint ? udcon (detach, ...) ?udint ?udien moreover, when frzclk is set, only the following interrupts may be triggered: ? wakeupi ?vbusti 21.8 speed control the speed selection (full speed or low speed) depends on the d+/d- pull-up. the lsm bit in udcon register allows to select an internal pull up on d- (low speed mode) or d+ (full speed mode) data lines. figure 21-11. device mode speed selection 21.9 memory management the controller only supports the follo wing memory allocation management. the reservation of a pipe or an endpoint can only be made in the increasing order (pipe/end- point 0 to the last pipe/endpoint). the firmware shall thus configure them in the same order. the reservation of a pipe or an endpoint ?k i ? is done when its alloc bit is set. then, the hard- ware allocates the memory and inserts it between the pipe/endpoints ?k i-1 ? and ?k i+1 ?. the ?k i+1 ? pipe/endpoint memory ?slides? up and its data is lost. note that the ?k i+2 ? and upper pipe/end- point memory does not slide. clearing a pipe enable (pen) or an endpoint enable (epen) does no t clear either its alloc bit, or its configuration (epsize/psi ze, epbk/pbk). to free its me mory, the firmware should clear alloc. then, the ?k i+1 ? pipe/endpoint memory automatically ?slides? down. note that the ?k i+2 ? and upper pipe/endpoint memory does not slide. r pu detach udcon.0 d+ d- r pu lsm udcon.2 ucap usb regulator
261 7766f?avr?11/10 atmega16/32u4 the following figure illustrates the allocation and reorganization of the usb memory in a typical example: table 21-1. allocation and reorganization usb memory flow ? first, endpoint 0 to endpoint 5 are configured, in the growing order. the memory of each is reserved in the dpram. ? then, the endpoint 3 is disabled (epen=0), but its memory reservation is internally kept by the controller. ? its alloc bit is cleared: the endpoint 4 ?s lides? down, but the endpoint 5 does not ?slide?. ? finally, if the firmware chooses to reconfigure the endpoint 3, with a bigger size. the controller reserved the memory after the endpoint 2 memory and automatically ?slide? the endpoint 4. the endpoint 5 does not move and a memory conflict appear, in that both endpoint 4 and 5 use a common area. the data of those endpoints are potentially lost. note that: ? the data of endpoint 0 are never lost whatever the activation or deactivation of the higher endpoint. its data is lost if it is deactivated. ? deactivate and reactivate the same endpoint with the same parameters does not lead to a ?slide? of the higher endpoints. for those endpoints, the data are preserved. ? cfgok is set by hardware even in the case where there is a ?conflict? in the memory allocation. 21.10 pad suspend the next figures illustra tes the pad behaviour: ? in the ?idle? mode, the pad is put in low power consumption mode. ? in the ?active? mode, the pad is working. free memory 0 1 2 3 4 5 epen=1 alloc=1 free memory 0 1 2 4 5 epen=0 (alloc=1) free memory 0 1 2 4 5 endpoints activation endpoint disable free its memory (alloc=0) free memory 0 1 2 3 (bigger size) 5 endpoint activatation lost memory 4 conflict
262 7766f?avr?11/10 atmega16/32u4 figure 21-12. pad behaviour the suspi flag indicated that a suspend state has been detected on the usb bus. this flag automatically put the usb pad in idle. the detection of a non-id le event sets the wakeupi flag and wakes-up the usb pad. moreover, the pad can also be put in the ?idle? mode if the detach bit is set. it come back in the active mode when the detach bit is cleared. 21.11 plug-in detection the usb connection is detected by the vbus pad, thanks to the following architecture: idle mode active mode usbe=1 & detach=0 & suspend usbe=0 | detach=1 | suspend suspi suspend detected = usb pad power down clear suspend by software resume = usb pad wake-up clear resume by software wakeupi pad status active power down active
263 7766f?avr?11/10 atmega16/32u4 figure 21-13. plug-in detection input block diagram the control logic of the vbus pad outputs a signal regarding the vbus voltage level: ? the ?session_valid? signal is active high when the voltage on the uvbus pad is higher or equal to 1.4v. if lower than 1.4v, the signal is not active. ? the vbus status bit is set when ?session_valid? signal is active (vbus > 1.4v). ? the vbusti flag is set each time the vbus state changes. ? the usb peripheral cannot attach to the bus while vbus bit is not set. 21.12 registers description 21.12.1 usb general registers ? 7-1 ? reserved these bits are reserved. do not modify these bits. ? 0 ? uvrege: usb pad regulator enable set to enable the usb pad regulator. clear to disable the usb pad regulator. ? 7 ? usbe: usb macro enable bit set to enable the usb controller. clear to disabl e and reset the usb controller, to disable the usb transceiver and to disable the usb controller clock inputs. ? 6 ? reserved the value read from these bits is always 0. do not set these bits. vbusti usbint.0 vbus vbus usbsta.0 vss vdd pad logic session_valid r pu r pu bit 7 6 5 4 321 0 - - - - - - - uvrege uhwcon read/write r/w r/w r r/w r r r r/w initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 321 0 usbe - frzclk otgpade - - - vbuste usbcon read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 1 0 0 0 0 0
264 7766f?avr?11/10 atmega16/32u4 ? 5 ? frzclk: freeze usb clock bit set to disable the clock inputs (the ?resume detection? is still active). this reduces the power consumption. clear to enable the clock inputs. ? 4 ? otgpade: vbus pad enable set to enable the vbus pad. clear to disable the vbus pad. note that this bit can be set/cleared even if usbe=0. that a llows the vbus detection even if the usb macro is disable. ? 3-1 ? reserved the value read from these bits is always 0. do not set these bits. ? 0 ? vbuste: vbus transition interrupt enable bit set this bit to enable the vbus transition interrupt generation. clear this bit to disable the vbus transition interrupt generation. ? 7-2 - reserved the value read from these bits is always 0. do not set these bits. ? 1 - id: id status this bit is always read as ?1?, it has been conserved for compatibility with at90usb64/128 (in which it indicates the va lue of the otg id pin). ? 0 ? vbus: vbus flag the value read from this bit indicates the state of the vbus pin. this bit can be used in device mode to monitor the usb bus connection state of the application. see section 21.11, page 262 for more details. 7-1 - reserved the value read from these bits is always 0. do not set these bits. ? 0 ? vbusti: ivbus transition interrupt flag set by hardware when a transition (high to low, low to high) has been detected on the vbus pad. shall be cleared by software. bit 76543 2 1 0 ----- -idvbususbsta read/writerrrrrrrr initial value00000 0 1 0 bit 76543210 -------vbustiusbint read/writerrrrrrr/wr/w initial value00000000
265 7766f?avr?11/10 atmega16/32u4 21.13 usb software operating modes depending on the usb operating mode, the software should perform some the following operations: power on the usb interface ? power-on usb pads regulator ? configure pll interface ?enable pll ? check pll lock ? enable usb interface ? configure usb interface (usb speed, endpoints configuration...) ? wait for usb vbus information connection ? attach usb device power off the usb interface ? detach usb interface ? disable usb interface ? disable pll ? disable usb pad regulator suspending the usb interface ? clear suspend bit ? freeze usb clock ? disable pll ? be sure to have interrupts enable to exit sleep mode ? make the mcu enter sleep mode resuming the usb interface ?enable pll ? wait pll lock ? unfreeze usb clock ? clear resume information
266 7766f?avr?11/10 atmega16/32u4 22. usb device operating modes 22.1 introduction the usb device controller supports full speed and low speed data transfers. in addition to the default control endpoint, it provides six other endp oints, which can be configured in control, bulk, interrupt or isochronous modes: ? endpoint 0:programmable size fifo up to 64 bytes, default control endpoint ? endpoints 1 programmable size fifo up to 256 bytes in ping-pong mode. ? endpoints 2 to 6: programmable size fifo up to 64 bytes in ping-pong mode. the controller starts in the ?idle? mode. in this mode, the pad consumption is reduced to the minimum. 22.2 power-on and reset the next diagram explains the usb device controller main states on power-on: figure 22-1. usb device controller states after reset the reset state of the device controller is: ? the macro clock is stopped in order to minimize the power consumption (frzclk set), ? the usb device controller internal state is reset (all the registers are reset to their default value. note that detach is set.) ? the endpoint banks are reset ? the d+ or d- pull up are not activated (mode detach) the d+ or d- pull-up will be activated as so on as the detach bit is cleared and vbus is present. the macro is in the ?idle? state after reset with a minimum power consumption and does not need to have the pll activated to enter this state. the usb device controller can at any time be reset by clearing usbe (disable usb interface). 22.3 endpoint reset an endpoint can be reset at any time by setting in the uerst register the bit corresponding to the endpoint (eprstx). this resets: ? the internal state machine on that endpoint, ? the rx and tx banks are cleared and their internal pointers are restored, reset idle hw reset usbe=0 usbe=0 usbe=1
267 7766f?avr?11/10 atmega16/32u4 ? the ueintx, uesta0x and uesta1x are restored to their reset value. the data toggle field remains unchanged. the other registers remain unchanged. the endpoint configuration remains active and the endpoint is still enabled. the endpoint reset may be associated with a clear of the data toggle command (rstdt bit) as an answer to the clear_feature usb command. 22.4 usb reset when an usb reset is detected on the usb line (s e0 state with a minimum duration of 2.5s), the next operations are performed by the controller: ? all the endpoints are disabled ? the default control endpoint remains configured (see section 22.3, page 266 for more details). if the cpu hardware reset function is activated (rstcpu bit set in udcon register), a reset is generated to the cpu core without disabling the usb controller (that follows the same behavior than after a standard usb end of reset, and remains attached). that feature may be used to enhance device reliability. 22.5 endpoint selection prior to any operation performed by the cpu, the endpoint must first be selected. this is done by setting the epnum2:0 bits (uenum regist er) with the endpoint number which will be man- aged by the cpu. the cpu can then access to the various endpoint registers and data. 22.6 endpoint activation the endpoint is maintained under reset as long as the epen bit is not set. the following flow must be respected in order to activate an endpoint:
268 7766f?avr?11/10 atmega16/32u4 figure 22-2. endpoint activation flow: as long as the endpoint is not correctly c onfigured (cfgok cleared), the hardware does not acknowledge the packets sent by the host. cfgok is will not be sent if the endpoint size parameter is bigger than the dpram size. a clear of epen acts as an endpoint reset (see se ction 22.3, page 266 for more details). it also performs the next operation: ? the configuration of the endpoint is kept (epsize, epbk, alloc kept) ? it resets the data toggle field. ? the dpram memory associated to the endpoint is still reserved. see section 21.9, page 260 for more details about the memory allocation/reorganization. 22.7 address setup the usb device address is set up according to the usb protocol: ? the usb device, after power-up, responds at address 0 ? the host sends a setup command (set_a ddress(addr)), ? the firmware handles this request, and records that address in uadd, but keep adden cleared, ? the usb device firmware sends an in command of 0 bytes (in 0 zero length packet), ? then, the firmware can enable the usb device address by setting adden. the only accepted address by the controller is the one stored in uadd. adden and uadd shall not be wr itten at the same time. uadd contains the default address 00h after a power-up or usb reset. endpoint activation cfgok=1 error no yes endpoint activated activate the endpoint select the endpoint epen=1 uenum epnum=x test the correct endpoint configuration uecfg1x alloc epsize epbk configure: - the endpoint size - the bank parametrization allocation and reorganization of the memory is made on-the-fly uecfg0x epdir eptype ... configure: - the endpoint direction - the endpoint type
269 7766f?avr?11/10 atmega16/32u4 adden is cleared by hardware: ? after a power-up reset, ? when an usb reset is received, ? or when the macro is disabled (usbe cleared) when this bit is cleared, the default device address 00h is used. 22.8 suspend, w ake-up and resume after a period of 3 ms during which the usb line was inactive, the controller switches to the full- speed mode and triggers (if enabled) the suspi (suspend) interrupt. the firmware may then set the frzclk bit. the cpu can also, depending on software architecture, enter in the idle mode to lower again the power consumption. there are two ways to recover from the ?suspend? mode: ? first one is to clear the frzclk bit. this is possible if the cpu is not in the idle mode. ? second way, if the cpu is ?idle?, is to e nable the wakeupi interrupt (wakeupe set). then, as soon as an non-idle signal is seen by the controller, the wakeupi interrupt is triggered. the firmware shall then clear the frzclk bit to restart the transfer. there are no relationship be tween the suspi interrupt and the wakeupi interrupt: the wake- upi interrupt is triggered as soon as there are non-idle patterns on the data lines. thus, the wakeupi interrupt can occurs even if the controller is not in the ?suspend? mode. when the wakeupi interrupt is tri ggered, if the suspi in terrupt bit was alread y set, it is cleared by hardware. when the suspi interrupt is trigge red, if the wakeupi interrupt bi t was already set, it is cleared by hardware. 22.9 detach the reset value of the detach bit is 1. it is possible to re-enumerate a device, simply by setting and clearing the detach bit (but firm- ware must take in account a debou ncing delay of some milliseconds). ? setting detach will disconnect the pull-up on the d+ or d- pad (depending on full or low speed mode selected). then, clea ring detach will connect the pu ll-up on the d+ or d- pad. figure 22-3. detach a device in full-speed: en=1 d + uvref d - detach, then attach en=1 d + uvref d -
270 7766f?avr?11/10 atmega16/32u4 22.10 remote wake-up the ?remote wake-up? (or ?upstream resume?) feature is the only operation allowed to be sent by the device on its own initiative. anyway, to do that, the device should first have received a device_remote_wakeup re quest from the host. ? first, the usb controller must have detected the ?suspend? state of the line: the remote wake- up can only be sent when a suspi flag is set. ? the firmware has then the ability to set rm wkup to send the ?ups tream resume? stream. this will automatically be done by the controller after 5ms of inactivity on the usb line. ? when the controller starts to send the ?upstream resume?, the uprsmi interrupt is triggered (if enabled). suspi is cleared by hardware. ? rmwkup is cleared by hardware at the end of the ?upstream resume?. ? if the controller detects a good ?end of resume? signal from the host, an eorsmi interrupt is triggered (if enabled). 22.11 stall request for each endpoint, the stall management is performed using 2 bits: ? stallrq (enable stall request) ? stallrqc (disable stall request) ? stalledi (stall sent interrupt) to send a stall handshake at the next request, the stallrq request bit has to be set. all fol- lowing requests will be handshak?ed with a stall until the stallrqc bit is set. setting stallrqc automatically clears the st allrq bit. the stallrqc bit is also immedi- ately cleared by hardware after being set by software. thus, the firmware will ne ver read this bit as set. each time the stall handshake is sent, the stal ledi flag is set by the usb controller and the epintx interrupt will be triggered (if enabled). the incoming packets will be discard ed (rxouti and rwal will not be set). the host will then send a command to reset the st all: the firmware just has to set the stall- rqc bit and to reset the endpoint. 22.11.1 special considerat ion for control endpoints a setup request is always ack?ed. if a stall request is set for a control endpoint and if a setup request occurs, the setup request has to be ack?ed and the stallrq request and stalledi sent flags are automati- cally reset (rxsetupi set, txin cleared, stalled cleared, txini cleared...). this management simplifies the enumeration process management. if a command is not sup- ported or contains an error, the firmware set the stall request flag and can return to the main task, waiting for the next setup request. this function is compliant with the chapter 8 test that may send extra status for a get_descriptor. the firmware sets the stall request just after receiving the status. all extra status will be automatically st all?ed until the ne xt setup request.
271 7766f?avr?11/10 atmega16/32u4 22.11.2 stall handshake and retry mechanism the retry mechanism has priority over the stall handshake. a stall handshake is sent if the stallrq request bit is set and if there is no retry required. 22.12 control endpoint management a setup request is always ack?ed. when a new setup packet is received, the rxstpi inter- rupt is triggered (if enabled). the rxouti interrupt is not triggered. the fifocon and rwal fields are irrelevant with control endpoints. the firmware shall thus never use them on that endpoints. when read, their value is always 0. control endpoints are managed by the following bits: ? rxstpi is set when a new setup is received. it shall be cleared by firmware to acknowledge the packet and to clear the endpoint bank . ? rxouti is set when a new out data is received. it shall be cleared by firmware to acknowledge the packet and to clear the endpoint bank . ? txini is set when the bank is ready to accept a new in packet. it shall be cleared by firmware to send the packet and to clear the endpoint bank . 22.12.1 control write the next figure shows a control wr ite transaction. during the stat us stage, the controller will not necessary send a nak at the first in token: ? if the firmware knows the exact number of descriptor bytes that must be read, it can then anticipate on the status stage and send a zlp for the next in token, ? or it can read the bytes and poll nakini, which tells that all the bytes have been sent by the host, and the transaction is now in the status stage. setup rxstpi rxouti txini usb line hw sw out hw sw out hw sw in in nak sw data setup status
272 7766f?avr?11/10 atmega16/32u4 22.12.2 control read the next figure shows a control read transaction. the usb controller has to manage the simulta- neous write requests from the cpu and the usb host: a nak handshake is always generated at the first status stage command. when the controller detect the status stage, all the data written by the cpu are erased, and clearing txini has no effects. the firmware checks if the transmission is complete or if the reception is complete. the out retry is always ack?ed. this reception: - set the rxouti flag (received out data) - set the txini flag (data sent, ready to accept new data) software algorithm: set transmit ready wait (transmit complete or receive complete) if receive complete, clear flag and return if transmit complete, continue once the out status stage has been received, the usb controller waits for a setup request. the setup request have priority over any other request and has to be ack?ed. this means that any other flag should be cleared and the fifo reset when a setup is received. warning: the byte counter is reset when the out zero length packet is received. the firm- ware has to take care of this. 22.13 out endpoint management out packets are sent by the host. all the data can be read by the cpu, which acknowledges or not the bank when it is empty. 22.13.1 overview the endpoint must be configured first. each time the current bank is full, the rxouti and the fifocon bits are set. this triggers an interrupt if the rxoute bit is set. the firmware can acknowledge the usb interrupt by clearing the rxouti bit. the firmware read the data and clear the fifocon bit in order to free the cur- rent bank. if the out endpoint is composed of multiple banks, clearing the fifocon bit will setup rxstpi rxouti txini usb line hw sw in hw sw in out out nak sw sw hw wr enable host wr enable cpu data setup status
273 7766f?avr?11/10 atmega16/32u4 switch to the next bank. the rxouti and fifocon bits are then updated by hardware in accor- dance with the status of the new bank. rxouti shall always be cleared before clearing fifocon. the rwal bit always reflects the state of the current bank. this bit is set if the firmware can read data from the bank, and cleared by hardware when the bank is empty. 22.13.2 detailed description 22.13.2.1 the data are read by the cpu, following the next flow: ? when the bank is filled by the ho st, an endpoint interrupt (epint x) is triggered, if enabled (rxoute set) and rxouti is set. the cpu can also poll rxouti or fifocon, depending on the software architecture, ? the cpu acknowledges the interrupt by clearing rxouti, ? the cpu can read the number of byte (n) in the current bank (n=byct), ? the cpu can read the data from the current bank (?n? read of uedatx), ? the cpu can free the bank by clearing fifocon when all the data is read, that is: ? after ?n? read of uedatx, ? as soon as rwal is cleared by hardware. if the endpoint uses 2 banks, the second one can be filled by the host while the current one is being read by the cpu. then, when the cpu clear fifocon, the next bank may be already ready and rxouti is set immediately. out data (to bank 0) ack rxouti fifocon hw out data (to bank 0) ack hw sw sw sw example with 1 out data bank read data from cpu bank 0 out data (to bank 0) ack rxouti fifocon hw out data (to bank 1) ack sw sw example with 2 out data banks read data from cpu bank 0 hw sw read data from cpu bank 0 read data from cpu bank 1 nak
274 7766f?avr?11/10 atmega16/32u4 22.14 in endpoint management in packets are sent by the usb device controller, upon an in request from the host. all the data can be written by the cpu, which acknowledge or not the bank when it is full.overview the endpoint must be configured first. the txini bit is set by hardware when the current bank becomes free. this triggers an interrupt if the txine bit is set. the fifocon bit is set at the same time. the cpu writes into the fifo and clears the fifocon bit to allow the usb controller to send the data. if the in endpoint is composed of multiple banks, this also switches to the next data bank. the txini and fifocon bits are automatically updated by hardware regarding the status of the next bank. txini shall always be cleared before clearing fifocon. the rwal bit always reflects the state of the current bank. this bit is set if the firmware can write data to the bank, and cleared by hardware when the bank is full. 22.14.1 detailed description the data are written by the cp u, following the next flow: ? when the bank is empty, an endpoint interrupt (epintx) is triggered, if enabled (txine set) and txini is set. the cpu can also poll txini or fifocon, depending the software architecture choice, ? the cpu acknowledges the interrupt by clearing txini, ? the cpu can write the data into the current bank (write in uedatx), ? the cpu can free the bank by clearing fifocon when all the data are written, that is: in data (bank 0) ack txini fifocon hw example with 1 in data bank write data from cpu bank 0 example with 2 in data banks sw sw sw sw in in data (bank 0) ack txini fifocon write data from cpu bank 0 sw sw sw sw in data (bank 1) ack write data from cpu bank 0 write data from cpu bank 1 sw hw write data from cpu bank0 nak
275 7766f?avr?11/10 atmega16/32u4 ? after ?n? write into uedatx ? as soon as rwal is cleared by hardware. if the endpoint uses 2 banks, the second one can be read by the host while the current is being written by the cpu. then, when the cpu clears fifocon, the next bank may be already ready (free) and txini is set immediately. 22.14.1.1 abort an ?abort? stage can be produced by the host in some situations: ? in a control transaction: zlp data out received during a in stage, ? in an isochronous in transaction: zlp data out received on the out endpoint during a in stage on the in endpoint ?... the killbk bit is used to kill the last ?written? ba nk. the best way to manage this abort is to per- form the following operations: table 22-1. abort flow 22.15 isochronous mode 22.15.1 underflow an underflow can occur during in stage if the host attempts to read a bank which is empty. in this situation, the underf i interrupt is triggered. an underflow can also occur during out stage if the host send a packet while the banks are already full. typically, he cpu is not fast enough. the packet is lost. it is not possible to have underflow error during out stage, in the cpu side, since the cpu should read only if the bank is ready to give data (rxouti=1 or rwal=1) endpoint abort abort done abort is based on the fact that no banks are busy, meaning that nothing has to be sent. disable the txini interrupt. endpoint reset nbusybk =0 yes clear ueienx. txine no killbk=1 killbk=1 yes kill the last written bank. wait for the end of the procedure. no
276 7766f?avr?11/10 atmega16/32u4 22.15.2 crc error a crc error can occur during out stage if the u sb controller detects a bad received packet. in this situation, the stalledi interrupt is triggered. this does not prevent the rxouti interrupt from being triggered. 22.16 overflow in control, isochronous, bulk or interrupt e ndpoint, an overflow can occur during out stage, if the host attempts to write in a bank that is too small for the packet. in this situation, the overfi interrupt is triggered (if enabled). the packet is acknowledged and the rxouti interrupt is also triggered (if enabled). the bank is filled with the fi rst bytes of the packet. it is not possible to have overflow error during in stage, in the cpu side, since the cpu should write only if the bank is ready to access data (txini=1 or rwal=1). 22.17 interrupts the next figure shows all the interrupts sources: figure 22-4. usb device controlle r interrupt system there are 2 kind of interrupts: processing (i.e. th eir generation are part of the normal processing) and exception (errors). processing interrupts are generated when: ? vbus plug-in detection (insert, remove)( vbusti ) ? upstream resume( uprsmi ) ? end of resume( eorsmi ) ? wake up( wakeupi ) ? end of reset (speed initialization)( eorsti ) ? start of frame( sofi , if fncerr=0) ? suspend detected after 3 ms of inactivity( suspi ) exception interrupts are generated when: ? crc error in frame number of sof( sofi , fncerr=1) uprsmi udint.6 uprsme udien.6 eorsmi udint.5 eorsme udien.5 wakeupi udint.4 wakeupe udien.4 eorsti udint.3 eorste udien.3 sofi udint.2 sofe udien.2 suspi udint.0 suspe udien.0 usb device interrupt
277 7766f?avr?11/10 atmega16/32u4 figure 22-5. usb device controller endpoint interrupt system processing interrupts are generated when: ? ready to accept in data( epintx , txini=1) ? received out data( epintx , rxouti=1) ? received setup( epintx , rxstpi=1) exception interrupts are generated when: ? stalled packet( epintx , stalledi=1) ? crc error on out in isochronous mode( epintx , stalledi=1) ? overflow in isochronous mode( epintx , overfi=1) ? underflow in isochronous mode( epintx , underfi=1) ? nak in sent( epintx , nakini=1) ? nak out sent( epintx , nakouti=1) 22.18 registers 22.18.1 usb device general registers epint ueint.x endpoint 0 endpoint 1 endpoint 2 endpoint 3 endpoint 4 endpoint 5 endpoint interrupt endpoint 6 flerre ueienx.7 overfi uestax.6 underfi uestax.5 nakini ueintx.6 nakine ueienx.6 nakouti ueintx.4 txstpe ueienx.4 rxstpi ueintx.3 txoute ueienx.3 rxouti ueintx.2 rxoute ueienx.2 stalledi ueintx.1 stallede ueienx.1 txini ueintx.0 txine ueienx.0 bit 76543 2 1 0 ----rstcpu lsm rmwkup detach udcon read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 1
278 7766f?avr?11/10 atmega16/32u4 ? 7-4 - reserved the value read from these bits is always 0. do not set these bits. ? 3 - rstcpu - usb reset cpu bit set this bit to 1 by firmware in order to rese t the cpu on the detection of a usb end of reset signal (without disabling the usb controller and attached state). this bit is reset when the usb controller is disabled, but is not affected by the cpu reset generated after a usb end of reset (remains enabled). ? 2 - lsm - usb device low speed mode selection when configured usb is configured in device mo de, this bit allows to select the usb the usb low speed or full speed mod. clear to select full speed mode (d+ internal pull- up will be activate with the attach bit will be set). set to select low spee d mode (d- internal pu ll-up will be activate with the attach bit will be set). this bit has no effect when the usb interface is configured in host mode. ? 1- rmwkup - remote wake-up bit set to send an ?upstream-resume? to the host for a remote wake-up (the suspi bit must be set). cleared by hardware when signalling fini shed. clearing by software has no effect. see section 22.10, page 270 for more details. ? 0 - detach - detach bit set to physically detach de device (disconnect internal pull-up on d+ or d-). clear to reconnect the device. see section 22.9, page 269 for more details. ? 7 - reserved the value read from this bits is always 0. do not set this bit. ? 6 - uprsmi - upstream resume interrupt flag set by hardware when the usb controller is sending a resume signal called ?upstream resume?. this triggers an u sb interrupt if uprsme is set. shall be cleared by software (usb clocks mu st be enabled before). setting by software has no effect. ? 5 - eorsmi - end of resume interrupt flag set by hardware when the usb controller detec ts a good ?end of resume? signal initiated by the host. this triggers an u sb interrupt if eorsme is set. shall be cleared by software. setting by software has no effect. bit 76543210 - uprsmi eorsmi wakeupi eorsti sofi - suspi udint read/write initial value00000000
279 7766f?avr?11/10 atmega16/32u4 ? 4 - wakeupi - wake-up cpu interrupt flag set by hardware when the usb controller is re-activated by a filtered non-idle signal from the lines (not by an upstream resume). this triggers an interrupt if wakeupe is set. shall be cleared by software (usb clock inputs must be enabled before). setting by software has no effect. see section 22.8, page 269 for more details. ? 3 - eorsti - end of reset interrupt flag set by hardware when an ?end of reset? has been detected by the usb controller. this triggers an usb interrupt if eorste is set. shall be cleared by software. setting by software has no effect. ? 2 - sofi - start of frame interrupt flag set by hardware when an usb ?start of frame? pid (sof) has been detected (every 1 ms). this triggers an usb inte rrupt if sofe is set. ? 1 - reserved the value read from this bits is always 0. do not set this bit ? 0 - suspi - suspend interrupt flag set by hardware when an usb ?suspend? ?idle bus for 3 frame periods: a j state for 3 ms) is detected. this triggers an u sb interrupt if suspe is set. shall be cleared by software. setting by software has no effect. see section 22.8, page 269 for more details. the interrupt bits are set even if their corresponding ?enable? bits is not set. ? 7 - reserved the value read from this bits is always 0. do not set this bit. ? 6 - uprsme - upstream resume interrupt enable bit set to enable the uprsmi interrupt. clear to disable the uprsmi interrupt. ? 5 - eorsme - end of resume interrupt enable bit set to enable the eorsmi interrupt. clear to disable the eorsmi interrupt. ? 4 - wakeupe - wake-up cpu interrupt enable bit set to enable the wakeupi interrupt. clear to disable the wakeupi interrupt. bit 76543210 - uprsme eorsme wakeupe eorste sofe - suspe udien read/write initial value 0 0 0 0 0 0 0 0
280 7766f?avr?11/10 atmega16/32u4 ? 3 - eorste - end of reset interrupt enable bit set to enable the eorsti interrupt. this bit is set after a reset. clear to disable the eorsti interrupt. ? 2 - sofe - start of frame interrupt enable bit set to enable the sofi interrupt. clear to disable the sofi interrupt. ? 1 - reserved the value read from this bits is always 0. do not set this bit ? 0 - suspe - suspend interrupt enable bit set to enable the suspi interrupt. clear to disable the suspi interrupt. ? 7 - adden - address enable bit set to activate the uadd (usb address). cleared by hardware . clearing by software has no effect. see section 22.7, page 268 for more details. ? 6-0 - uadd6:0 - usb address bits load by software to configure the device address. ? 7-3 - reserved the value read from these bits is always 0. do not set these bits. ? 2-0 - fnum10:8 - frame number upper value set by hardware. these bits are the 3 msb of the 11-bits frame number information. they are provided in the last received sof packet. fnum is updated if a corrupted sof is received. bit 76543210 adden uadd6:0 udaddr read/write w r/w r/w r/w r/w r/w r/w r/w initial val- ue 00000000 bit 76543 2 1 0 ----- fnum10:8 udfnumh read/write r r r r r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 fnum7:0 udfnuml read/writerrrrrrrr initial value00000000
281 7766f?avr?11/10 atmega16/32u4 ? frame number lower value set by hardware. these bits are the 8 lsb of the 11-bits frame number information. ? 7-5 - reserved the value read from these bits is always 0. do not set these bits. ? 4 - fncerr -frame number crc error flag set by hardware when a corrupted frame number in start of frame packet is received. this bit and the sofi interrupt are updated at the same time. ? 3-0 - reserved the value read from these bits is always 0. do not set these bits. 22.18.2 usb device endpoint registers ? 7-3 - reserved the value read from these bits is always 0. do not set these bits. ? 2-0 - epnum2:0 endpoint number bits load by software to select the number of the endpoint which shall be accessed by the cpu. see section 22.5, page 267 for more details. epnum = 111b is forbidden. ? 7 - reserved the value read from these bits is always 0. do not set these bits. ? 6-0 - eprst6:0 - endpoint fifo reset bits set to reset the selected endpoint fifo prior to any other operation, upon hardware reset or when an usb bus reset has been received. see section 22.3, page 266 for more information bit 76543210 - - - fncerr - - - - udmfn read/w rite r initial value 00000000 bit 76543210 - - - - - epnum2:0 uenum read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 - eprst6 eprst5 eprst4 eprst 3 eprst2 eprst1 eprst0 uerst read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
282 7766f?avr?11/10 atmega16/32u4 then, clear by software to complete the reset operation and start using the endpoint. ? 7-6 - reserved the value read from these bits is always 0. do not set these bits. ? 5 - stallrq - stall request handshake bit set to request a stall answer to the host for the next handshake. cleared by hardware when a new setup is received. clearin g by software has no effect. see section 22.11, page 270 for more details. ? 4 - stallrqc - stall re quest clear handshake bit set to disable the stall handshake mechanism. cleared by hardware immediately after the set. clearing by software has no effect. see section 22.11, page 270 for more details. 3 ? rstdt - reset data toggle bit set to automatically clear the data toggle sequence: for out endpoint: the next received packet will have the data toggle 0. for in endpoint: the next packet to be sent will have the data toggle 0. cleared by hardware instantaneously. the firmware does not have to wait that the bit is cleared. clearing by software has no effect. ? 2 - reserved the value read from these bits is always 0. do not set these bits. ? 1 - reserved the value read from these bits is always 0. do not set these bits. ? 0 - epen - endpoint enable bit set to enable the endpoint according to the devic e configuration. endpoi nt 0 shall always be enabled after a hardware or usb reset and participate in the device configuration. clear this bit to disable the endpoint. see section 22.6, page 267 for more details. ? 7-6 - eptype1:0 - endpoint type bits set this bit according to the endpoint configuration: bit 76543210 - - stallrq stallrqc rstdt - - epen ueconx read/write r r w w w r r r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 eptype1:0 - - - - - epdir uecfg0x read/writer/wr/wrrrrrr/w initial value 0 0 0 0 0 0 0 0
283 7766f?avr?11/10 atmega16/32u4 00b: control10b: bulk 01b: isochronous11b: interrupt ? 5-1 - reserved the value read from these bits is always 0. do not set these bits. ? 0 - epdir - endpoint direction bit set to configure an in direction for bulk, interrupt or isochronous endpoints. clear to configure an out direction for bulk, interrupt, isochronous or control endpoints. ? 7 - reserved the value read from these bits is always 0. do not set these bits. ? 6-4 - epsize2:0 - endpoint size bits set this bit according to the endpoint size: 000b: 8 bytes100b: 128 bytes 001b: 16 bytes101b: 256 bytes 010b: 32 bytes110b: 512 bytes 011b: 64 bytes111b: reserved. do not use this configuration. ? 3-2 - epbk1:0 - endpoint bank bits set this field according to the endpoint size: 00b: one bank 01b: double bank 1xb: reserved. do not use this configuration. ? 1 - alloc - endpoint allocation bit set this bit to allocate the endpoint memory. clear to free the endpoint memory. see section 22.6, page 267 for more details. ? 0 - reserved the value read from these bits is always 0. do not set these bits. bit 7 6 5 4 3 2 1 0 - epsize2:0 epbk1:0 alloc - uecfg1x read/write r r/w r/w r/w r/w r/w r/w r initial value 0 0 0 0 0 0 0 0 bit 76543210 cfgok overfi underfi - dtseq1:0 nbusybk1:0 uesta0x read/write r r/w r/w r/w r r r r initial value 0 0 0 0 0 0 0 0
284 7766f?avr?11/10 atmega16/32u4 ? 7 - cfgok - configuration status flag set by hardware when the endpoint x size parameter (epsize) and the bank parametrization (epbk) are correct compared to the max fifo capacity and the max number of allowed bank. this bit is updated when the bit alloc is set. if this bit is cleared, the us er should reprogram the uecfg1x register with correct epsize and epbk values. ? 6 - overfi - overflow error interrupt flag set by hardware when an overflow error occu rs in an isochronous endpoint. an interrupt (epintx) is triggered (if enabled). see section 22.15, page 275 for more details. shall be cleared by software. setting by software has no effect. ? 5 - underfi - flow error interrupt flag set by hardware when an underflow error occurs in an isochronous endpoint. an interrupt (epintx) is triggered (if enabled). see section 22.15, page 275 for more details. shall be cleared by software. setting by software has no effect. ? 4 - reserved the value read from these bits is always 0. do not set these bits. ? 3-2 - dtseq1:0 - data toggle sequencing flag set by hardware to indicate the pid data of the current bank: 00b data0 01b data1 1xb reserved. for out transfer, this value indicates the last data toggle received on the current bank. for in transfer, it indicates the to ggle that will be used for the next packet to be se nt. this is not relative to the current bank. ? 1-0 - nbusybk1:0 - busy bank flag set by hardware to indicate the number of busy bank. for in endpoint, it indicates the number of busy ba nk(s), filled by the user, ready for in transfer. for out endpoint, it indicates the number of busy bank(s) filled by out transaction from the host. 00b all banks are free 01b 1 busy bank 10b 2 busy banks 11b reserved.
285 7766f?avr?11/10 atmega16/32u4 ? 7-3 - reserved the value read from these bits is always 0. do not set these bits. ? 2 - ctrldir - control direction (flag, and bit for debug purpose) set by hardware after a setup packet, and gives the direction of the following packet: - 1 for in endpoint - 0 for out endpoint. can not be set or cleared by software. ? 1-0 - currbk1:0 - current bank (all endpoints except control endpoint) flag set by hardware to indicate the number of the current bank: 00b bank0 01b bank1 1xb reserved. can not be set or cleared by software. ? 7 - fifocon - fifo control bit for out and setup endpoint: set by hardware when a new out message is stored in the current bank, at the same time than rxout or rxstp. clear to free the current bank and to switch to the following bank. setting by software has no effect. for in endpoint: set by hardware when the current bank is free, at the same time than txin. clear to send the fifo data and to switch the bank. setting by software has no effect. ? 6 - nakini - nak in received interrupt flag set by hardware when a nak handshake has been sent in response of a in request from the host. this triggers an usb in terrupt if nakine is sent. shall be cleared by software. setting by software has no effect. bit 76543 2 10 - - - - - ctrldir currbk1:0 uesta1x read/write r r r r r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 fifocon nakini rwal nakouti rxstp i rxouti stalledi txini ueintx read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
286 7766f?avr?11/10 atmega16/32u4 ? 5 - rwal - read/write allowed flag set by hardware to signal: - for an in endpoint: the current bank is not full i.e. the firmware can push data into the fifo, - for an out endpoint: the current bank is not empt y, i.e. the firmware can read data from the fifo. the bit is never set if stallrq is set, or in case of error. cleared by hardware otherwise. this bit shall not be used for the control endpoint. ? 4 - nakouti - nak out re ceived interrupt flag set by hardware when a nak handshake has been sent in response of a out/ping request from the host. this triggers an u sb interrupt if nakoute is sent. shall be cleared by software. setting by software has no effect. ? 3 - rxstpi - received setup interrupt flag set by hardware to signal that the current bank contains a new valid setup packet . an inter- rupt (epintx) is triggered (if enabled). shall be cleared by software to handshake the interrupt. setting by software has no effect. this bit is inactive (cleared) if the endpoint is an in endpoint. ? 2 - rxouti / killbk - received out data interrupt flag set by hardware to signal that the current bank contains a new packet. an interrupt (epintx) is triggered (if enabled). shall be cleared by software to handshake the interrupt. setting by software has no effect. kill bank in bit set this bit to kill the last written bank. cleared by hardware when th e bank is killed. clearing by software has no effect. see page 275 for more details on the abort. ? 1 - stalledi - stalledi interrupt flag set by hardware to signal that a stall hands hake has been sent, or that a crc error has been detected in a out isochronous endpoint. shall be cleared by software. setting by software has no effect. ? 0 - txini - transmitter ready interrupt flag set by hardware to signal that the current bank is free and can be filled. an inte rrupt (epintx) is triggered (if enabled). shall be cleared by software to handshake the interrupt. setting by software has no effect. this bit is inactive (cleared) if the endpoint is an out endpoint.
287 7766f?avr?11/10 atmega16/32u4 ? 7 - flerre - flow error interrupt enable flag set to enable an endpoint interrupt (epintx) when overfi or underfi are sent. clear to disable an endpoint interrupt (epi ntx) when overfi or underfi are sent. ? 6 - nakine - nak in interrupt enable bit set to enable an endpoint interr upt (epintx) when nakini is set. clear to disable an endpoint interr upt (epintx) when nakini is set. ? 5 - reserved the value read from these bits is always 0. do not set these bits. ? 4 - nakoute - nak out interrupt enable bit set to enable an endpoint interr upt (epintx) when nakouti is set. clear to disable an endpoint interr upt (epintx) when nakouti is set. ? 3 - rxstpe - received setup interrupt enable flag set to enable an endpoint interrupt (epintx) when rxstpi is sent. clear to disable an endpoint interrup t (epintx) when rxstpi is sent. ? 2 - rxoute - received out data interrupt enable flag set to enable an endpoint interrupt (epintx) when rxouti is sent. clear to disable an endpoint interrupt (epintx) when rxouti is sent. ? 1 - stallede - stalled interrupt enable flag set to enable an endpoint interrupt (epintx) when stalledi is sent. clear to disable an endpoint interrupt (epintx) when stalledi is sent. ? 0 - txine - transmitter ready interrupt enable flag set to enable an endpoint interrupt (epintx) when txini is sent. clear to disable an endpoint interrupt (epintx) when txini is sent. ? 7-0 - dat7:0 -data bits set by the software to read/write a byte from/to the endpoint fifo selected by epnum. bit 76543210 flerre nakine - nakoute rxstpe rxoute stallede txine ueienx read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 dat d7 dat d6 dat d5 dat d4 dat d3 dat d2 dat d1 dat d0 uedatx read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
288 7766f?avr?11/10 atmega16/32u4 ? 7-3 - reserved the value read from these bits is always 0. do not set these bits. ? 2-0 - byct10:8 - byte count (high) bits set by hardware. this field is the msb of the byte count of the fifo endpoint. the lsb part is provided by the uebclx register. ? 7-0 - byct7:0 - byte count (low) bits set by the hardware. byct10:0 is: - (for in endpoint) increased after each writing into the endpoint and decremented after each byte sent, - (for out endpoint) increased after each byte sent by the host, and decremented after each byte read by the software. ? 7 - reserved the value read from these bits is always 0. do not set these bits. ? 6-0 - epint6:0 - endpoint interrupts bits set by hardware when an interrupt is triggered by the ueintx register and if the corresponding endpoint interrupt enable bit is set. cleared by hardware when the interrupt source is served. bit 76543 2 1 0 - - - - - byct d10 byct d9 byct d8 uebchx read/writerrrrr r r r initial value00000 0 0 0 bit 76543210 byct d7 byct d6 byct d5 byct d4 byct d3 byct d2 byct d1 byct d0 uebclx read/writerrrrrrrr initial value00000000 bit 76543210 - epint d6 epint d5 epint d4 epint d3 epint d2 epint d1 epint d0 ueint read/writerrrrrrrr initial value00000000
289 7766f?avr?11/10 atmega16/32u4 23. analog comparator the analog comparator compares the input val ues on the positive pin ain+ and negative pin ain-. when the voltage on the positive pin ain+ is higher than the voltage on the negative pin ain-, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. th e user can select interrupt triggering on com- parator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 23-1 . ain+ can be connected either to the ain0 (pe6) pin, or to the internal bandgap reference. ain- can only be connected to the adc multiplexer. the power reduction adc bit, pradc, in ?power reduction register 0 - prr0? on page 46 must be disabled by writing a logical zero to be able to use the adc input mux. figure 23-1. analog comparator block diagram (2) notes: 1. see table 23-2 on page 291 . 2. refer to ?pinout atmega16u4/atmega32u4? on page 3 and table 10-3 on page 72 for ana- log comparator pin placement. 23.0.1 adc control and status register b ? adcsrb ? bit 6 ? acme: analog comparator multiplexer enable when this bit is written logic one and the adc is switched off (aden in adcsra is zero), the adc multiplexer is connected to the negative input to the analog comparator. when this bit is written logic zero, the bandgap reference is connected to the negative input of the analog com- parator ( see ?internal voltage reference? on page 54. ). for a detailed description of this bit, see ?analog comparator multiplexed input? on page 291 . 23.0.2 analog comparator control and status register ? acsr acbg bandgap reference adc multiplexer output acme aden (1) ain+ ain- bandgap reference bit 7 6543210 adhsm acme mux5 ? adts3 adts2 adts1 adts0 adcsrb read/write r r/w r r r r/w r/w r/w initial value0 0000000 bit 76543210 acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 n/a 0 0 0 0 0
290 7766f?avr?11/10 atmega16/32u4 ? bit 7 ? acd: analog comparator disable when this bit is written logic one , the power to the analog comparator is switched off. this bit can be set at any time to tu rn off the analog com parator. this will reduce power consumption in active and idle mode. when changing the acd bit, the analog comparator interrupt must be disabled by clearing the acie bit in acsr. otherwise an interrupt can occur when the bit is changed. ? bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap reference vo ltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is ap plied to the positive input of the analog compar- ator. see ?internal voltage reference? on page 54. ? bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interr upt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when executing the corresponding inter- rupt handling vector. alternatively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable when the acie bit is written logic one and the i-bi t in the status register is set, the analog com- parator interrupt is activated. when written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be trig- gered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the compar ator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. when written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator trigger the timer/counter1 input capture interrupt, the icie1 bit in the timer interrupt mask register (timsk1) must be set. ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator interrupt. the different settings are shown in table 23-1 . when changing the acis1/acis0 bits, the analog comparator interrupt must be disabled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. table 23-1. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle. 01reserved 1 0 comparator interrupt on falling output edge. 1 1 comparator interrupt on rising output edge.
291 7766f?avr?11/10 atmega16/32u4 23.1 analog comparator multiplexed input it is possible to select any of the adc13..0 pins to replace the negative input to the analog com- parator. the adc multiplexer is used to select this input, and consequently, the adc must be switched off to utilize this feature. if the analog comparator multiplexer enable bit (acme in adcsrb) is set and the adc is switched off (aden in adcsra is zero), and mux2..0 in admux select the input pin to replace the negati ve input to the analog comparator, as shown in table 23-2 . if acme is cleared or aden is set, the bandgap reference is applied to the negative input to the analog comparator. 23.1.1 digital input disab le register 1 ? didr1 ? bit 0 ? ain0d: ain0 digital input disable when this bit is written logic one, the digital in put buffer on the ain0 pin is disabled. the corre- sponding pin register bit will alwa ys read as zero when this bit is set. when an analog signal is applied to the ain0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. table 23-2. analog comparator multiplexed input acme aden mux2..0 analog comparator negative input 0 x xxx bandgap ref. 1 1 xxx bandgap ref. 1 0 000 adc0 1 0 001 adc1 10010 n/a 10011 1 0 100 adc4 1 0 101 adc5 1 0 110 adc6 1 0 111 adc7 bit 76543210 ? ? ? ? ? ? ? ain0d didr1 read/writerrrrrrrr/w initial value00000000
292 7766f?avr?11/10 atmega16/32u4 24. analog to digital converter - adc 24.1 features ? 10/8-bit resolution ? 0.5 lsb integral non-linearity ? 2 lsb absolute accuracy ? 65 - 260 s conversion time ? up to 15 ksps at maximum resolution ? twelve multiplexed single-ended input channels ? one differential amplifier providin g gain of 1x - 10x - 40x - 200x ? temperature sensor ? optional left adjustment for adc result readout ? 0 - v cc adc input voltage range ? selectable 2.56 v adc reference voltage ? free running or single conversion mode ? adc start conversion by auto tr iggering on interrupt sources ? interrupt on adc conversion complete ? sleep mode no ise canceler the atmega16u4/atmega32u4 features a 10-bit su ccessive approximation adc. the adc is connected to an 12-channel analog multiplexer which allows six single-ended voltage inputs constructed from several pins of port b, d and f. the single-ended voltage inputs refer to 0v (gnd). the device also supports 32 differential voltage input combinations, thanks to a differential amplifier equipped with a programmable gain stage, providing amplification steps of 0 db (1x), 10 db (10x), 16db (40x) or 23db (200x) on the di fferential input voltage before the a/d conver- sion. two differential analog input channels share a common negative terminal (adc0/adc1), while any other adc input can be selected as the positive input terminal. if 1x, 10x or 40x gain is used, 8-bit resolution can be expected. if 200x ga in is used, 7-bit resolution can be expected. the adc contains a sample and hold circuit whic h ensures that the input voltage to the adc is held at a constant level during conversion . a block diagram of the adc is shown in figure 24-1 . the adc has a separate analog supply voltage pin, av cc . av cc must not differ more than 0.3v from v cc . see the paragraph ?adc noise canceler? on page 301 on how to connect this pin. internal reference voltages of nominally 2.56v or av cc are provided on-chip. the voltage refer- ence may be externally decoupled at the aref pi n by a capacitor for better noise performance.
293 7766f?avr?11/10 atmega16/32u4 figure 24-1. analog to digital converter block schematic adc conversion complete irq 8-bit data bus 15 0 adc multiplexer select (admux) adc ctrl. & status register (adcsra) adc data register (adch/adcl) mux2 adie adate adsc aden adif adif mux1 mux0 adps0 adps1 adps2 mux3 conversion logic 10-bit dac + - sample & hold comparator internal reference mux decoder mux4 avcc adc 9 adc8 adc7 adc6 adc5 adc4 adc1 adc0 refs0 refs1 adlar + - channel selection gain selection adc[ 9 :0] adc multiplexer output differential amplifier aref bandgap reference prescaler single ended / differential selection gnd pos. input mux neg. input mux trigger select adts[3:0] interrupt flags adhsm start adc13 adc12 adc11 adc10 mux5 temperature sensor
294 7766f?avr?11/10 atmega16/32u4 24.2 operation the adc converts an analog input voltage to a 10-bit digital value through successive approxi- mation. the minimum value represents gnd and the maximum value represents the voltage on the aref pin minus 1 lsb. optionally, av cc or an internal 2.56v reference voltage may be con- nected to the aref pin by writing to the refsn bits in the admux register. the internal voltage reference may thus be decoupled by an external capacitor at the aref pin to improve noise immunity. the analog input channel and diff erential gain are selected by writing to the mux bits in admux. any of the adc input pins, as well as gnd and a fixed bandgap voltage reference, can be selected as single ended inputs to the adc. a selection of adc input pins can be selected as positive and negative inputs to the differential amplifier. the adc is enabled by setting the adc enable bit, aden in adcsra. voltage reference and input channel selections will not go into effect until aden is set. the adc does not consume power when aden is cleared, so it is recommended to switch off the adc before entering power saving sleep modes. the adc generates a 10-bit result which is pr esented in the adc data registers, adch and adcl. by default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the adlar bit in admux. if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch, to ensure that the content of the data registers belongs to the same conversion. once adcl is read, adc access to data registers is blocked. this means that if adcl has been read, and a conversion completes before adch is read, neither register is updated and the result fr om the conversion is lost. when adch is read, adc access to the adch and ad cl registers is re-enabled. the adc has its own interrupt which can be tr iggered when a conversion completes. the adc access to the data registers is prohibited between reading of adch and adcl, the interrupt will trigger even if the result is lost. 24.3 starting a conversion a single conversion is started by writing a l ogical one to the adc start conversion bit, adsc. this bit stays high as long as the conversi on is in progress and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversion is in progress, the adc will finish the current conv ersion before performing the channel change. alternatively, a conversion can be triggered automatically by various sources. auto triggering is enabled by setting the adc auto trigger enable bi t, adate in adcsra. the trigger source is selected by setting the adc trig ger select bits, adts in adcsrb (see description of the adts bits for a list of the trigger sources). when a positive edge occurs on the selected trigger signal, the adc prescaler is reset and a conversion is st arted. this provides a method of starting con- versions at fixed intervals. if th e trigger signal is still set when the conversion completes, a new conversion will not be star ted. if another positive edge occurs on the trigger si gnal during con- version, the edge will be ignored. note that an interrupt flag will be set even if the specific interrupt is disabled or the global interrupt enable bit in sreg is cleared. a conversion can thus be triggered without causing an interrupt. however, the interrupt flag must be cleared in order to trigger a new conversion at the next interrupt event.
295 7766f?avr?11/10 atmega16/32u4 figure 24-2. adc auto trigger logic using the adc interrupt flag as a trigger source makes the adc start a new conversion as soon as the ongoing conversion has finished. the adc then operates in free running mode, con- stantly sampling and updating the adc data register. the first conversion must be started by writing a logical one to the adsc bit in adcs ra. in this mode the adc will perform successive conversions independently of whether the a dc interrupt flag, adif is cleared or not. if auto triggering is enabled, single conversi ons can be started by writing adsc in adcsra to one. adsc can also be used to determine if a conversion is in progress. the adsc bit will be read as one during a conversion, independently of how the conversion was started. 24.4 prescaling and conversion timing figure 24-3. adc prescaler by default, the successive approximation circuitry requires an input clock frequency between 50 khz and 200 khz to get maximum resolution. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be higher than 200 khz to get a higher sample rate. alter- natively, setting the adhsm bit in adcsrb allows an increased adc clock frequency at the expense of higher power consumption. the adc module contains a prescaler, which generates an acceptable adc clock frequency from any cpu frequency above 100 khz. the presca ling is set by the adps bits in adcsra. the prescaler starts counting from the moment the adc is switched on by setting the aden bit adsc adif source 1 source n adts[2:0] conversion logic prescaler start clk adc . . . . edge detector adate 7-bit adc prescaler adc clock source ck adps0 adps1 adps2 ck/128 ck/2 ck/4 ck/8 ck/16 ck/32 ck/64 reset aden start
296 7766f?avr?11/10 atmega16/32u4 in adcsra. the prescaler keeps running for as lo ng as the aden bit is set, and is continuously reset when aden is low. when initiating a single ended conversion by se tting the adsc bit in adcsra, the conversion starts at the following rising edge of the adc clock cycle. see ?differential channels? on page 297 for details on differential conversion timing. a normal conversion takes 13 adc clock cycles. the first conversion after the adc is switched on (aden in adcsra is set) takes 25 adc clock cycles in order to initialize the analog circuitry. the actual sample-and-hold takes place 1.5 adc clock cycles after the start of a normal conver- sion and 13.5 adc clock cycles after the start of an first conv ersion. when a conversion is complete, the result is written to the adc data re gisters, and adif is set. in single conversion mode, adsc is cleared simultaneously. the software may then set adsc again, and a new conversion will be init iated on the first rising adc clock edge. when auto triggering is used, the prescaler is reset when the trigger event occurs. this assures a fixed delay from the trigger event to the start of conversion. in this mode, the sample-and-hold takes place two adc clock cycles after the rising edge on the trigger source signal. three addi- tional cpu clock cycles are used for synchronization logic. in free running mode, a new conversion will be started immediately after the conversion com- pletes, while adsc remains high. for a summary of conversion times, see table 24-1 . figure 24-4. adc timing diagram, first conver sion (single conversion mode) figure 24-5. adc timing diagram, single conversion sign and msb of result lsb of result adc clock adsc sample & hold adif adch adcl cycle number aden 1 212 13 14 15 16 17 18 1 9 20 21 22 23 24 25 1 2 first conversion next conversion 3 mux and refs update mux and refs update conversion complete 1 2 3 4 5 6 7 8 9 10 11 12 13 sign and msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 3 sample & hold mux and refs update conversion complete mux and refs update
297 7766f?avr?11/10 atmega16/32u4 figure 24-6. adc timing diagram, auto triggered conversion figure 24-7. adc timing diagram, free running conversion 24.4.1 differential channels when using differential channels, certain aspe cts of the conversion need to be taken into consideration. differential conversions are synchronized to the internal clock ck adc2 equal to half the adc clock frequency. this synchroniza tion is done automatically by the adc interface in such a way that the sample-and-hold occurs at a specific phase of ck adc2 . a conversion initiated by the user (i.e., all single conversions, and the first free running conversion) when ck adc2 is low will take the same amount of time as a single ended conversion (1 3 adc clock cycles from the next prescaled clock cycle). a conversion initiated by the user when ck adc2 is high will take 14 adc table 24-1. adc conversion time condition first conversion normal conversion, single ended auto triggered convertion sample & hold (cycles from start of convention) 14.5 1.5 2 conversion time (cycles) 25 13 13.5 1 2 3 4 5 6 7 8 9 10 11 12 13 sign and msb of result lsb of result adc clock trigger source adif adch adcl cycle number 12 one conversion next conversion conversion complete prescaler reset adate prescaler reset sample & hold mux and refs update 11 12 13 sign and msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 34 conversion complete sample & hold mux and refs update
298 7766f?avr?11/10 atmega16/32u4 clock cycles due to the synchronization mechanism. in free running mode, a new conversion is initiated immediately after the previous conversion completes, and since ck adc2 is high at this time, all automatically started (i.e., all but the fi rst) free running conversions will take 14 adc clock cycles. if differential channels are used and conversions ar e started by auto triggering, the adc must be switched off between conversions. when auto triggering is used, the adc prescaler is reset before the conversion is started. since the stage is dependent of a stable adc clock prior to the conversion, this conversion w ill not be valid. by disabling a nd then re-enabling the adc between each conversion (writing aden in adcsra to ?0? then to ?1?), only extended conversions are performed. the result from the extended conversions will be valid. see ?prescaling and conver- sion timing? on page 295 for timing details. the gain stage is optimized for a bandwidth of 4 khz at all gain settings. higher frequencies may be subjected to non-linear amplification. an exte rnal low-pass filter should be used if the input signal contains higher frequency components th an the gain stage bandwidth. note that the adc clock frequency is independent of the gain stage bandwidth limitation. e.g. the adc clock period may be 6 s, allowing a channel to be sampled at 12 ksps, regardless of the bandwidth of this channel. 24.5 changing channel or reference selection the muxn and refs1:0 bits in the admux register are single buffered through a temporary register to which the cpu has random access. this ensures that the channels and reference selection only takes place at a safe point dur ing the conversion. the channel and reference selection is continuously updated until a conversion is started. once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the adc. con- tinuous updating resumes in the last adc clock cycle before the conversion completes (adif in adcsra is set). note that the conversion star ts on the following rising adc clock edge after adsc is written. the user is thus advised not to write new channel or reference selection values to admux until one adc clock cycle after adsc is written. if auto triggering is used, the exact time of t he triggering event can be indeterministic. special care must be taken when updating the admux register, in order to control which conversion will be affected by the new settings. if both adate and aden is written to one, an interrupt event can occur at any time. if the admux register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. admux can be safely updated in the following ways: a. when adate or aden is cleared. b. during conversion, minimum one adc clock cycle after the trigger event. c. after a conversion, before the interrupt flag used as trigger source is cleared. when updating admux in one of these conditions, the new settings will affect the next adc conversion. special care should be taken when changing differential channels. once a differential channel has been selected, the stage may take as much as 125 s to stabilize to the new value. thus conversions should not be started within the firs t 125 s after selecting a new differential chan- nel. alternatively, conversion results obt ained within this period should be discarded. the same settling time should be observed for th e first differential conversion after changing adc reference (by changing the refs1:0 bits in admux).
299 7766f?avr?11/10 atmega16/32u4 the settling time and gain stage bandwidth is independent of the adhsm bit setting. 24.5.1 adc input channels when changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: ? in single conversion mode, always select the channel before starting the conversion. the channel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the conversion to complete before changing the channel selection. ? in free running mode, always select the channel before starting the first conversion. the channel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the first conversion to complete, and then change the channel selection. since the next conversion has already started automatically, the next result will reflect the previous channel selection. su bsequent conversions will reflect the new channel selection. when switching to a differential gain channel, the first conversion result may have a poor accu- racy due to the required settling time for the automatic offset cancellation circuitry. the user should preferably disregard the first conversion result. 24.5.2 adc voltage reference the reference voltage for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in code s close to 0x3ff. v ref can be selected as either av cc , internal 2.56v reference, or external aref pin. av cc is connected to the adc through a passive switch. the internal 2.56v reference is gener- ated from the internal bandgap reference (v bg ) through an internal amplifier. in either case, the external aref pin is directly connected to the adc, and the reference voltage can be made more immune to noise by connecting a capacitor between the aref pin and ground. v ref can also be measured at the aref pin with a high impedance voltmeter. note that v ref is a high impudent source, and only a capacitive load should be connected in a system. if the user has a fixed voltage source connected to the aref pin, the user may not use the other reference voltage options in the ap plication, as they will be shorte d to the external voltage. if no external voltage is applied to the aref pin, the user may switch between av cc and 2.56v as reference selection. the first adc conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result. if differential channels are used, the selected reference should not be closer to av cc than indi- cated in table 29-5 on page 384 . 24.6 temperature sensor the atmega16u4/atmega32u4 includes an on-chip temperature sensor, whose the value can be read through the a/d converter. the temperature measurement is based on an on-ch ip temperature sensor that is coupled to a single ended adc input. mux[5..0] bits in admux register enables the temperature sensor. the nternal 2.56v voltage reference must also be selected for the adc voltage reference source in he temperature sensor measurement. when the temperature sensor is enabled, the adc con- verter can be used in single conversion mode to measure the voltage over the temperature sensor.
300 7766f?avr?11/10 atmega16/32u4 the temperature sensor and its internal driver are enabled when admux value selects the tem- perature sensor as adc input. the propagation delay of this driver is approximatively 2s. therefore two successive conv ersions are required. the correct temper ature measurement will be the second one. one can also reduce this timing to one conversion by setting the admux during the previous conversion. indeed the admux can be programmed to select the temperature sensor just after the beginning of the previous conversion start event and t hen the driver will be enabled 2 s before sampling and hold phase of temperature sensor measurement. 24.6.1 sensor calibration the sensor initial to lerance is large (+/-10c), but its characte ristic is linear. thus, if the applica- tion requires accuracy, the firmware must include a calibration stage to use the sensor for direct temperature measurement. another application of this sensor may concern the internal calib rated rc oscillator, whose the frequency can be adjusted by the user through the osccal register (see section 6.5. 1 ?oscilla- tor calibration register ? osccal? on page 32 ). during the production, a calibration is done at two temperatures (+25c and +85c, with a tolerance of +/-10c (1) ). at each temperature, the temperature sensor value t i is measured and stored in eeprom memory (2) , and the osccal calibration value o i (i.e. the value that should be set in osccal register at this temperature to have an accurate 8mhz output) is stored in another memory zone. thanks to these four values and the linear characteristics of the temperature sensor and internal rc oscillator, firmware can easily recalibrate th e rc oscillator on -the-go in func tion of the tem- perature sensor measure (3) (an application note describes the operation): figure 24-8. linear characterization of osccal in function of t measurement from adc notes: 1. the temperature sensor calibration values cannot be used to do accurate temperature mea- surements since the calibration temperature during production is not accurate (+/- 10c) 2. be aware that if eesave fuse is left unprogrammed, any chip erase operation will clear the temperature sensor calibration values contained in eeprom memory. 3. accuracy results after a soft ware recalibration of osccal in function of t will be given when device will be fully characterized. osccal t(adc o 1 o 2 t 1 t 2
301 7766f?avr?11/10 atmega16/32u4 24.7 adc noise canceler the adc features a noise canceler that enables conversion during sleep mode to reduce noise induced from the cpu core and other i/o peripherals. the noise canceler can be used with adc noise reduction and idle mode. to make use of this feature, the following procedure should be used: a. make sure that the adc is enabled and is not busy converting. single conversion mode must be selected and the adc conversion complete interrupt must be enabled. b. enter adc noise reduction mode (or idle mode). the adc will start a conversion once the cpu has been halted. c. if no other interrupts occur before the adc conversion completes, the adc inter- rupt will wake up the cpu and execute the adc conversion complete interrupt routine. if another interrupt wakes up the cpu before the adc conversion is com- plete, that interrupt will be executed, and an adc conversion complete interrupt request will be generated when the adc conversion completes. the cpu will remain in active mode until a new sleep command is executed. note that the adc will not be automatically turned off when entering other sleep modes than idle mode and adc noise reduction mode. the user is advised to write zero to aden before enter- ing such sleep modes to avoid excessive power consumption. if the adc is enabled in such sleep modes and the user wants to perform differential conver- sions, the user is advised to switch the adc off and on after waking up from sleep to prompt an extended conversion to get a valid result. 24.7.1 analog input circuitry the analog input circuitry for single ended channels is illustrated in figure 24-9. an analog source applied to adcn is subjected to the pin capacitance and input leakage of that pin, regard- less of whether that channel is selected as input for the adc. when the channel is selected, the source must drive the s/h capacitor through the series resistance (combined resistance in the input path). the adc is optimized for analog signals wit h an output impedance of approximately 10 k or less. if such a source is used, the sampling time will be negligible. if a source with higher imped- ance is used, the sampling time will depend on how long time the source nee ds to charge the s/h capacitor, with can vary widely. the user is recommended to only use low impedance sources with slowly varying signals, since this mi nimizes the required charge transfer to the s/h capacitor. if differential gain channels are used, the input circuitry looks somewhat different, although source impedances of a few hundred k or less is recommended. signal components higher th an the nyquist frequency (f adc /2) should not be present for either kind of channels, to avoid distortion from unpredictable signal convolution. the user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the adc.
302 7766f?avr?11/10 atmega16/32u4 figure 24-9. analog input circuitry 24.7.2 analog noise canceling techniques digital circuitry inside and outside the device ge nerates emi which might affect the accuracy of analog measurements. if conversion accuracy is critical, the noise level can be reduced by applying the following techniques: a. keep analog signal paths as short as possible. make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digi- tal tracks. b. the av cc pin on the device should be connected to the digital v cc supply voltage via an lc network as shown in figure 24-10 . c. use the adc noise canceler function to reduce induced noise from the cpu. d. if any adc port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. figure 24-10. adc power connections note: the same circuitry should be used for avcc filtering on the adc8-adc13 side adcn i ih 1..100 k c s/h = 14 pf v cc /2 i il vcc gnd 100nf analog ground plane (adc0) pf0 (adc7) pf7 (adc1) pf1 (adc4) pf4 (adc5) pf5 (adc6) pf6 aref gnd avcc 34 35 36 37 38 3 9 40 41 42 43 44 1 10h
303 7766f?avr?11/10 atmega16/32u4 24.7.3 offset compensation schemes the gain stage has a built-in offset cancellation circ uitry that nulls the offset of differential mea- surements as much as possible. the remaining offset in the analog path can be measured directly by selecting the same channel for both differential inputs. this offset residue can be then subtracted in software from the measurement resu lts. using this kind of software based offset correction, offset on any channel can be reduced below one lsb. 24.7.4 adc accuracy definitions an n-bit single-ended adc converts a voltage linearly between gnd and v ref in 2 n steps (lsbs). the lowest code is read as 0, and the highest code is read as 2 n -1. several parameters describe the deviation from the ideal behavior: ? offset: the deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 lsb). ideal value: 0 lsb. figure 24-11. offset error ? gain error: after adjusting for offset, the gain error is found as the deviation of the last transition (0x3fe to 0x3ff) compared to the ideal transition (at 1.5 lsb below maximum). ideal value: 0 lsb output code v ref input voltage ideal adc actual adc offset error
304 7766f?avr?11/10 atmega16/32u4 figure 24-12. gain error ? integral non-linearity (inl): after adjusting for offset and gain error, the inl is the maximum deviation of an actual transition compared to an ideal transition for any code. ideal value: 0 lsb. figure 24-13. integral non-linearity (inl) ? differential non-linearity (dnl): the maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. output code v ref input voltage ideal adc actual adc gain error output code v ref input voltage ideal adc actual adc inl
305 7766f?avr?11/10 atmega16/32u4 figure 24-14. differential non-linearity (dnl) ? quantization error: due to the quantization of the input voltage into a finite number of codes, a range of input voltages (1 lsb wide) will code to the same value. always 0.5 lsb. ? absolute accuracy: the maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. this is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. ideal value: 0.5 lsb. 24.8 adc conversion result after the conversion is complete (adif is high ), the conversion result can be found in the adc result registers (adcl, adch). for single ended conversion, the result is: where v in is the voltage on the selected input pin and v ref the selected voltage reference (see table 24-3 on page 307 and table 24-4 on page 308 ). 0x000 represents analog ground, and 0x3ff represents the selected reference voltage minus one lsb. if differential channels are used, the result is: where v pos is the voltage on the positive input pin, v neg the voltage on the negative input pin, gain the selected gain factor and v ref the selected voltage reference. the result is presented in two?s complement form, from 0x200 (-512d) through 0x1ff (+511d). note that if the user wants to perform a quick polarity check of the result, it is sufficient to read the msb of the result (adc9 in adch). if the bit is one, th e result is negative, and if this bit is zero, the result is posi- tive. figure 24-15 shows the decoding of the differential input range. table 82 shows the resulting output codes if the differential input channel pair (adcn - adcm) is selected with a reference voltage of v ref . output code 0x3ff 0x000 0 v ref input voltage dnl 1 lsb adc v in 1023 ? v ref -------------------------- = adc v pos v neg ? () gain 512 ?? v ref ------------------------------------------------------------------------ =
306 7766f?avr?11/10 atmega16/32u4 figure 24-15. differential measurement range example 1: ? admux = 0xe9, mux5 = 0 (adc1 - adc0, 10x gain, 2.56v reference, left adjusted result) ? voltage on adc1 is 300 mv, voltage on adc0 is 500 mv. ? adcr = 512 * 10 * (300 - 500) / 2560 = -400 = 0x270 table 24-2. correlation between input voltage and output codes v adcn read code corresponding decimal value v adcm + v ref /gain 0x1ff 511 v adcm + 0.999 v ref /gain 0x1ff 511 v adcm + 0.998 v ref /gain 0x1fe 510 ... ... ... v adcm + 0.001 v ref /gain 0x001 1 v adcm 0x000 0 v adcm - 0.001 v ref /gain 0x3ff -1 ... ... ... v adcm - 0.999 v ref /gain 0x201 -511 v adcm - v ref /gain 0x200 -512 0 output code 0x1ff 0x000 v ref differential input voltage (volts) 0x3ff 0x200 - v ref
307 7766f?avr?11/10 atmega16/32u4 ? adcl will thus read 0x00, and adch will read 0x9c. writing zero to adlar right adjusts the result: adcl = 0x70, adch = 0x02. example 2: ? admux = 0xf0, mux5 = 0 (adc0 - adc1, 1x gain, 2.56v reference, left adjusted result) ? voltage on adc0 is 300 mv, voltage on adc1 is 500 mv. ? adcr = 512 * 1 * (300 - 500) / 2560 = -41 = 0x029 . ? adcl will thus read 0x40, and adch will read 0x0a. writing zero to adlar right adjusts the result: adcl = 0x00, adch = 0x29. 24.9 adc register description 24.9.1 adc multiplexer selection register ? admux ? bit 7:6 ? refs1:0: reference selection bits these bits select the voltage reference for the adc, as shown in table 24-3 . if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). the internal voltage reference options may not be used if an external reference voltage is being applied to the aref pin. ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data register. write one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adlar bit will affect t he adc data register immediately, regardless of any ongoing conver- sions. for a complete description of this bit, see ?the adc data register ? adcl and adch? on page 311 . ? bits 4:0 ? mux4:0: analog channel selection bits the value of these bits selects which combination of analog inputs are connected to the adc. these bits also select the gain for the differential channels. see table 24-4 for details. if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). bit 76543210 refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 admux read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 24-3. voltage reference selections for adc refs1 refs0 voltage reference selection 0 0 aref, internal vref turned off 01av cc with external capacitor on aref pin 10reserved 1 1 internal 2.56v voltage reference with external capacitor on aref pin
308 7766f?avr?11/10 atmega16/32u4 table 24-4. input channel and gain selections mux5..0 (1) single ended input positive differential input negative differential input gain 000000 adc0 n/a 000001 adc1 000010 n/a 000011 000100 adc4 000101 adc5 000110 adc6 000111 adc7 001000 n/a n/a n/a n/a 001001 adc1 adc0 10x 001010 n/a n/a n/a 001011 adc1 adc0 200x 001100 n/a 001101 001110 001111 010000 adc0 adc1 1x
309 7766f?avr?11/10 atmega16/32u4 010001 n/a n/a 010010 010011 010100 adc4 adc1 1x 010101 adc5 adc1 1x 010110 adc6 adc1 1x 010111 adc7 adc1 1x 011000 n/a 011001 011010 011011 011100 011101 011110 1.1v (v band gap ) 011111 0v (gnd) 100000 adc8 100001 adc9 100010 adc10 100011 adc11 100100 adc12 100101 adc13 100110 n/a adc1 adc0 40x 100111 temperature sensor 101000 n/a adc4 adc0 10x 101001 adc5 adc0 10x 101010 adc6 adc0 10x 101011 adc7 adc0 10x 101100 adc4 adc1 10x 101101 adc5 adc1 10x 101110 adc6 adc1 10x 101111 adc7 adc1 10x 110000 adc4 adc0 40x 110001 adc5 adc0 40x 110010 adc6 adc0 40x 110011 adc7 adc0 40x table 24-4. input channel and gain selections (continued) mux5..0 (1) single ended input positive differential input negative differential input gain
310 7766f?avr?11/10 atmega16/32u4 note: 1. mux5 bit make part of adcsrb register 24.9.2 adc control and status register a ? adcsra ? bit 7 ? aden: adc enable writing this bit to one enables the adc. by writi ng it to zero, the adc is turned off. turning the adc off while a conversion is in prog ress, will terminate this conversion. ? bit 6 ? adsc: adc start conversion in single conversion mode, write this bit to one to start each conversion. in free running mode, write this bit to one to start the first conversion. the first conversion after adsc has been written after the adc has been enabled, or if adsc is written at the same time as the adc is enabled, will take 25 adc clock cycles instead of the norma l 13. this first conversi on performs initializa- tion of the adc. adsc will read as one as long as a conversion is in progress. when the co nversion is complete, it returns to zero. writing zero to this bit has no effect. ? bit 5 ? adate: adc auto trigger enable when this bit is written to on e, auto triggering of the adc is enabled. the adc will start a con- version on a positive edge of the selected trigger signal. the trigger source is selected by setting the adc trigger select bits, adts in adcsrb. ? bit 4 ? adif: adc interrupt flag this bit is set when an adc conversion completes and the data registers are updated. the adc conversion complete interrupt is executed if the adie bit and the i-bit in sreg are set. adif is cleared by hardware when executing th e corresponding interrupt handling vector. alter- natively, adif is cleared by writing a logical one to the flag. beware that if doing a read-modify- 110100 n/a adc4 adc1 40x 110101 adc5 adc1 40x 110110 adc6 adc1 40x 110111 adc7 adc1 40x 111000 adc4 adc0 200x 111001 adc5 adc0 200x 111010 adc6 adc0 200x 111011 adc7 adc0 200x 111100 adc4 adc1 200x 111101 adc5 adc1 200x 111110 adc6 adc1 200x 111111 adc7 adc1 200x table 24-4. input channel and gain selections (continued) mux5..0 (1) single ended input positive differential input negative differential input gain bit 76543210 aden adsc adate adif adie adps2 adps1 adps0 adcsra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
311 7766f?avr?11/10 atmega16/32u4 write on adcsra, a pending interrupt can be dis abled. this also applies if the sbi and cbi instructions are used. ? bit 3 ? adie: adc interrupt enable when this bit is written to one and the i-bit in sreg is set, the adc conversion complete inter- rupt is activated. ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the xtal frequency and the input clock to the adc. 24.9.3 the adc data register ? adcl and adch 24.9.3.1 adlar = 0 24.9.3.2 adlar = 1 when an adc conversion is complete, the result is found in these two registers. if differential channels are used, the result is presented in two?s complement form. when adcl is read, the adc data register is not updated unt il adch is read. consequently, if the result is left adjusted and no more than 8-bit precision (7 bit + sign bit for differential input table 24-5. adc prescaler selections adps2 adps1 adps0 division factor 000 2 001 2 010 4 011 8 100 16 101 32 110 64 1 1 1 128 bit 151413121110 9 8 ? ? ? ? ? ? adc9 adc8 adch adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl bit 76543210 read/write rrrrrrrr rrrrrrrr initial value00000000 00000000 bit 151413121110 9 8 adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch adc1 adc0 ? ????? adcl bit 76543210 read/write rrrrrrrr rrrrrrrr initial value00000000 00000000
312 7766f?avr?11/10 atmega16/32u4 channels) is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch. the adlar bit in admux, and the muxn bits in admux affect the way the result is read from the registers. if adlar is set, the result is left adjusted. if adla r is cleared (default), the result is right adjusted. ? adc9:0: adc conversion result these bits represent the result from the conversion, as detailed in ?adc conversion result? on page 305 . 24.9.4 adc control and status register b ? adcsrb ? bit 7 ? adhsm: adc high speed mode writing this bit to one enables the adc high speed mode. this mode enables higher conversion rate at the expense of higher power consumption. ? bit 5 ? mux5: analog channel additional selection bits this bit make part of mux5:0 bits of adrcsrb and admux register, that select the combina- tion of analog inputs connected to the adc (inc luding differential amplifier configuration). ? bit 3:0 ? adts3:0: adc auto trigger source if adate in adcsra is written to one, the value of these bits selects which source will trigger an adc conversion. if adate is cleared, the adts3:0 settings will have no effect. a conversion will be triggered by the rising edge of the selected inte rrupt flag. note that switching from a trig- ger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. if aden in adcsra is set, this will start a conversion. switching to free running mode (adts[3:0]=0) will not cause a trigger event, even if t he adc interrupt flag is set . bit 76543210 adhsm acme mux5 ? adts3 adts2 adts1 adts0 adcsrb read/write r/w r/w r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 24-6. adc auto trigger source selections adts3 adts2 adts1 adts0 trigger source 0 0 0 0 free running mode 0 0 0 1 analog comparator 0 0 1 0 external interrupt request 0 0 0 1 1 timer/counter0 compare match 0 1 0 0 timer/counter0 overflow 0 1 0 1 timer/counter1 compare match b 0 1 1 0 timer/counter1 overflow 0 1 1 1 timer/counter1 capture event 1 0 0 0 timer/counter4 overflow
313 7766f?avr?11/10 atmega16/32u4 24.9.5 digital input disable register 0 ? didr0 ? bit 7:4, 1:0 ? adc7d..4d - adc1d..0d : adc7:4 - adc1:0 digi tal input disable when this bit is written logic one, the digita l input buffer on the corresponding adc pin is dis- abled. the corresponding pin regist er bit will always read as zero when this bit is set. when an analog signal is applied to the adc7..4 / adc1..0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 24.9.6 digital input disable register 2 ? didr2 ? bit 5:0 ? adc13d..adc8d: adc 13:8 digital input disable when this bit is written logic one, the digita l input buffer on the corresponding adc pin is dis- abled. the corresponding pin regist er bit will always read as zero when this bit is set. when an analog signal is applied to the adc13..8 pin and t he digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 1 0 0 1 timer/counter4 compare match a 1 0 1 0 timer/counter4 compare match b 1 0 1 1 timer/counter4 compare match d table 24-6. adc auto trigger source selections (continued) adts3 adts2 adts1 adts0 trigger source bit 76543210 adc7d adc6d adc5d adc4d - - adc1d adc0d didr0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 - - adc13d adc12d adc11d adc10d adc9d adc8d didr2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
314 7766f?avr?11/10 atmega16/32u4 25. jtag interface and on-chip debug system 25.0.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan ca pabilities according to the i eee std. 1149.1 (jtag) standard ? debugger access to: ? all internal peripheral units ? internal and external ram ? the internal register file ?program counter ? eeprom and flash memories ? extensive on-chip debug support for break conditions, including ? avr break instruction ? break on change of program memory flow ? single step break ? program memory break points on single address or address range ? data memory break points on si ngle address or address range ? programming of flash, eeprom , fuses, and lock bits th rough the jtag interface ? on-chip debugging supported by avr studio ? 25.1 overview the avr ieee std. 1149.1 compliant jtag interface can be used for ? testing pcbs by using the jtag boundary-scan capability ? programming the non-volatile memories, fuses and lock bits ? on-chip debugging a brief description is given in the following se ctions. detailed descriptions for programming via the jtag interface, and using the boundary-scan chain can be found in the sections ?program- ming via the jtag interface? on page 365 and ?ieee 1149.1 (jtag) bo undary-scan? on page 320 , respectively. the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third party vendors only. figure 25-1 shows a block diagram of the jtag interface and the on-chip debug system. the tap controller is a state machine controlled by the tck and tms signals. the tap controller selects either the jtag instruction register or one of several data registers as the scan chain (shift register) between the tdi ? input and tdo ? output. the instruction register holds jtag instructions controlling the be havior of a data register. the id-register, bypass register, and the bou ndary-scan chain are the data registers used for board-level testing. the jtag programming interface (actually consisting of several physical and virtual data registers) is used for serial programming via the jtag interface. the internal scan chain and break point scan chain are used for on-chip debugging only. 25.2 test access port ? tap the jtag interface is accessed through four of the avr?s pins. in jtag terminology, these pins constitute the test access port ? tap. these pins are: ? tms: test mode select. this pin is used for navigating through the tap-controller state machine. ? tck: test clock. jtag operation is synchronous to tck.
315 7766f?avr?11/10 atmega16/32u4 ? tdi: test data in. serial input data to be shifted in to the instruction register or data register (scan chains). ? tdo: test data out. serial output data from instruction register or data register. the ieee std. 1149.1 also specifies an optional tap signal; trst ? test reset ? which is not provided. when the jtagen fuse is unprogrammed, these four tap pins are normal port pins, and the tap controller is in reset. when programmed, the input tap signals are internally pulled high and the jtag is enabled for boundary-scan and programming. the device is shipped with this fuse programmed. for the on-chip debug system, in addition to the jtag interface pins, the reset pin is moni- tored by the debugger to be able to detect external reset sources. the debugger can also pull the reset pin low to reset the whole system, assuming only open collectors on the reset line are used in the application. figure 25-1. block diagram tap controller tdi tdo tck tms flash memory avr cpu digital peripheral units jtag / avr core communication interface breakpoint unit flow control unit ocd status and control internal scan chain m u x instruction register id register bypass register jtag programming interface pc instruction address data breakpoint scan chain address decoder analog peripherial units i/o port 0 i/o port n boundary scan chain analog inputs control & clock lines device boundary
316 7766f?avr?11/10 atmega16/32u4 figure 25-2. tap controller state diagram 25.3 tap controller the tap controller is a 16-state finite state machine that controls the operation of the boundary- scan circuitry, jtag programming circuitry, or on-chip debug system. the state transitions depicted in figure 25-2 depend on the signal present on tm s (shown adjacent to each state transition) at the time of the rising edge at tck. the initial state after a power-on reset is test- logic-reset. as a definition in this document, the lsb is shifted in and out first for all shift registers. assuming run-test/idle is the present state, a typical scenario for using the jtag interface is: ? at the tms input, apply the sequence 1, 1, 0, 0 at the rising edges of tck to enter the shift instruction register ? shift-ir state. while in this state, shift the four bits of the jtag instructions into the jtag instruction register from the tdi input at the rising edge of tck. the tms input must be held low during input of the 3 lsbs in order to remain in the shift-ir state. the msb of the instruction is shifted in when this state is left by setting tms high. while the instruction is shifted in from the tdi pin, the captured ir-state 0x01 is shifted out on the tdo pin. the jtag instruction selects a particular data register as path between tdi and tdo and controls the circuitry surrounding the selected data register. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
317 7766f?avr?11/10 atmega16/32u4 ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. the instruction is latched onto the parallel output from the shift register path in the update-ir state. the exit-ir, pause-ir, and exit2-ir states are only used for navigating the state machine. ? at the tms input, apply the sequence 1, 0, 0 at the rising edges of tck to enter the shift data register ? shift-dr state. while in th is state, upload the selected data register (selected by the present jtag instruction in the jtag instruction register) from the tdi input at the rising edge of tck. in order to remain in the shift-dr state, the tms input must be held low during input of all bits except the msb. the msb of the data is shifted in when this state is left by setting tms high. while the data register is shifted in from the tdi pin, the parallel inputs to the data register captured in the capture-dr state is shifted out on the tdo pin. ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. if the selected data register has a latched parallel-output, the latching takes place in the update-dr state. the exit-dr, pause-dr, and exit2-dr states are only used for navigating the state machine. as shown in the state diagram, the run-test/idle state need not be entered between selecting jtag instruction and using data registers, and some jtag instructions may select certain functions to be performed in the run-test/idle, making it unsuitable as an idle state. note: independent of the initial state of the tap c ontroller, the test-logic-r eset state can always be entered by holding tms high for five tck clock periods. for detailed information on the jtag specification, refer to the literature listed in ?bibliography? on page 319 . 25.4 using the b oundary-scan chain a complete description of the boundary-sc an capabilities are gi ven in the section ?ieee 1149.1 (jtag) boundary-scan? on page 320 . 25.5 using the on-c hip debug system as shown in figure 25-1 , the hardware support for on-chi p debugging consists mainly of ? a scan chain on the interface between the internal avr cpu and the internal peripheral units. ? break point unit. ? communication interface between the cpu and jtag system. all read or modify/write operations needed for implementing the debugger are done by applying avr instructions via the internal avr cpu scan chain. the cpu sends the result to an i/o memory mapped location which is part of the communication interface between the cpu and the jtag system. the break point unit implements break on change of program flow, single step break, two program memory break points, and two combined break points. together, the four break points can be configured as either: ? 4 single program memory break points. ? 3 single program memory break point + 1 single data memory break point. ? 2 single program memory break points + 2 single data memory break points. ? 2 single program memory break points + 1 program memory break point with mask (?range break point?).
318 7766f?avr?11/10 atmega16/32u4 ? 2 single program memory break points + 1 data memory break point with mask (?range break point?). a debugger, like the avr studio, may however use one or more of these resources for its inter- nal purpose, leaving less flexibility to the end-user. a list of the on-chip debug specific jtag instructions is given in ?on-chip debug specific jtag instructions? on page 318 . the jtagen fuse must be programmed to enable the jtag test access port. in addition, the ocden fuse must be programmed and no lock bits must be set for the on-chip debug system to work. as a security feature, the on-chip debug system is disabled when either of the lb1 or lb2 lock bits are set. otherwise, the on-chi p debug system would have provided a back-door into a secu red device. the avr studio enables the user to fully contro l execution of programs on an avr device with on-chip debug capability, avr in- circuit emulator, or the built-i n avr instruction set simulator. avr studio ? supports source level execution of assembly programs assembled with atmel corporation?s avr assembler and c programs compiled with third part y vendors? compilers. avr studio runs under microsoft ? windows ? 95/98/2000 and microsoft windows nt ? . for a full description of the avr studio, please re fer to the avr studio user guide. only high- lights are presented in this document. all necessary execution commands are available in avr studio, both on source level and on disassembly level. the user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop th e execution, and reset the execution target. in addition, the user can have an unlimited number of code break points (using the break instruction) and up to two data memory break points, alternatively combined as a mask (range) break point. 25.6 on-chip debug specific jtag instructions the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third party vendors only. instruction opcodes are listed for reference. 25.6.1 private0; 0x8 private jtag instruction for accessing on-chip debug system. 25.6.2 private1; 0x9 private jtag instruction for accessing on-chip debug system. 25.6.3 private2; 0xa private jtag instruction for accessing on-chip debug system. 25.6.4 private3; 0xb private jtag instruction for accessing on-chip debug system.
319 7766f?avr?11/10 atmega16/32u4 25.7 on-chip debug related register in i/o memory 25.7.1 on-chip debug register ? ocdr the ocdr register provides a co mmunication channel from the running pr ogram in the micro- controller to the debugger. the cpu can transfer a byte to the debugger by writing to this location. at the same time, an in ternal flag; i/o debug register dirty ? idrd ? is set to indicate to the debugger that the register has been written. when the cpu reads the ocdr register the 7 lsb will be from the ocdr regi ster, while the msb is the idrd bit. the debugger clears the idrd bit when it has read the information. in some avr devices, this register is shared with a standard i/o location. in this case, the ocdr register can only be accessed if the ocden fuse is programmed, and the debugger enables access to the ocdr register. in all other cases, the standard i/o location is accessed. refer to the debugger documentation for further information on how to use this register. 25.8 using the jtag pr ogramming capabilities programming of avr parts via jtag is performed via the 4-pin jtag port, tck, tms, tdi, and tdo. these are the only pins that need to be controlled/observed to perform jtag program- ming (in addition to power pins). it is not requi red to apply 12v externally. the jtagen fuse must be programmed and the jtd bit in the mcucr register must be cleared to enable the jtag test access port. the jtag programmi ng capability supports: ? flash programming and verifying. ? eeprom programming and verifying. ? fuse programming and verifying. ? lock bit programming and verifying. the lock bit security is exactly as in parallel programming mode. if the lock bits lb1 or lb2 are programmed, the ocden fuse cannot be programmed unless first doing a chip erase. this is a security feature that ensures no back-door exists for reading out the content of a secured device. the details on programming through the jtag interface and programming specific jtag instructions are given in the section ?programming via the jtag interface? on page 365 . 25.9 bibliography for more information about general boundary-scan, the following literature can be consulted: ? ieee: ieee std. 1149.1-1 990. ieee standard test acce ss port and boundary-scan architecture, ieee, 1993. ? colin maunder: the board designers guide to testable logic circuits, addison-wesley, 1992. bit 7 6543210 msb/idrd lsb ocdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
320 7766f?avr?11/10 atmega16/32u4 26. ieee 1149.1 (jtag) boundary-scan 26.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities acco rding to the jtag standard ? full scan of all port functions as well as analog circuitry having off-chip connections ? supports the optional idcode instruction ? additional public avr_reset instruction to reset the avr 26.2 system overview the boundary-scan chain has the capability of drivin g and observing the logi c levels on the digi- tal i/o pins, as well as the boundary between digi tal and analog logic for analog circuitry having off-chip connections. at system level, all ics having jtag capabilities ar e connected serially by the tdi/tdo signals to form a long shift register. an external controller sets up the devices to drive values at their output pins, and observe the input values received from other devices. the controller compares the received data with the expected result. in this way, boundary-scan pro- vides a mechanism for testing interconnections and integrity of components on printed circuits boards by using the four tap signals only. the four ieee 1149.1 defined mandatory jtag in structions idcode, bypass, sample/pre- load, and extest, as well as the avr specif ic public jtag instruction avr_reset can be used for testing the print ed circuit board. initial scanning of the data register path will show the id-code of the device, since idcode is the default jtag instruction. it may be desirable to have the avr device in reset during test mode. if not reset, inputs to the device may be deter- mined by the scan operations, and the internal software may be in an undetermined state when exiting the test mode. en tering reset, the outputs of any po rt pin will instantly enter the high impedance state, making the highz instruction redundant. if needed, the bypass instruction can be issued to make the shortest possible scan chain through the device. the device can be set in the reset state either by pulling the external reset pin low, or issuing the avr_reset instruction with appropriate setting of the reset data register. the extest instruction is used for sampling external pins and loading output pins with data. the data from the output latch will be driven out on the pins as soon as the extest instruction is loaded into the jtag ir-register. therefore, the sample/preload should also be used for setting initial values to the scan ring, to avoid damaging the board when issuing the extest instruction for the first time. sample/preload c an also be used for taking a snapshot of the external pins during normal operation of the part. the jtagen fuse must be pr ogrammed and the jtd bit in the i/o register mcucr must be cleared to enable the jtag test access port. when using the jtag interface for boundary-scan, using a jtag tck clock frequency higher than the internal chip frequency is possible. the chip clock is not required to run. 26.3 data registers the data registers relevant for boundary-scan operations are: ? bypass register ? device identification register ? reset register ? boundary-scan chain
321 7766f?avr?11/10 atmega16/32u4 26.3.1 bypass register the bypass register consists of a single shift register stage. when the bypass register is selected as path between tdi and tdo, the register is reset to 0 when leaving the capture-dr controller state. the bypass register can be used to shorten the scan chain on a system when the other devices are to be tested. 26.3.2 device identification register figure 26-1 shows the structure of the de vice identification register. figure 26-1. the format of the device identification register 26.3.2.1 version version is a 4-bit number identifying the revision of the component. the jtag version number follows the revision of the device. revision a is 0x0, revision b is 0x1 and so on. 26.3.2.2 part number the part number is a 16-bit code identifying the component. the jtag part number for atmega16u4/atmega32u4 is listed in table 26-1 . 26.3.2.3 manufacturer id the manufacturer id is a 11-bit code identifying the manufacturer. the jtag manufacturer id for atmel is listed in table 26-2 . 26.3.3 reset register the reset register is a test data register used to reset the part. since the avr tri-states port pins when reset, the reset register can also replace the function of the unimplemented optional jtag instruction highz. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high value present in the reset register. depending on the fuse set- tings for the clock options, the part will remain reset for a reset time-out period (refer to ?clock sources? on page 28 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 26-2 . msb lsb bit 31 28 27 12 11 1 0 device id version part number manufacturer id 1 4 bits 16 bits 11 bits 1-bit table 26-1. avr jtag part number part number jtag part number (hex) avr usb 0x9782 table 26-2. manufacturer id manufacturer jtag manufacturer id (hex) at m e l 0 x 0 1 f
322 7766f?avr?11/10 atmega16/32u4 figure 26-2. reset register 26.3.4 boundary-scan chain the boundary-scan chain has the capability of driv ing and observing the lo gic levels on the dig- ital i/o pins, as well as the boundary between di gital and analog logic for analog circuitry having off-chip connections. see ?boundary-scan chain? on page 324 for a complete description. 26.4 boundary-scan specifi c jtag instructions the instruction register is 4-bit wide, suppor ting up to 16 instructions. listed below are the jtag instructions useful for boundary-scan operation. note that the optional highz instruction is not implemented, but all output s with tri-state capa bility can be set in high-impedance state by using the avr_reset instruction, since the initial state for all port pins is tri-state. as a definition in this datasheet, the lsb is shifted in and out first for all shift registers. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. 26.4.1 extest; 0x0 mandatory jtag instruction for selecting the boundary-scan chain as data register for testing circuitry external to the avr package. for port- pins, pull-up disable, output control, output data, and input data are all accessible in the scan chain. for analog ci rcuits having off-chip connections, the interface between the analog and th e digital logic is in the scan chain. the con- tents of the latched outputs of the boundary-scan chain is driven out as soon as the jtag ir- register is loaded with the extest instruction. the active states are: ? capture-dr: data on the external pins are sampled into the boundary-scan chain. ? shift-dr: the internal scan chain is shifted by the tck input. ? update-dr: data from the scan chain is applied to output pins. 26.4.2 idcode; 0x1 optional jtag instruction selecting the 32 bit id-register as data register. the id-register consists of a version number, a device number and the manufacturer code chosen by jedec. this is the default inst ruction after power-up. dq from tdi clockdr avr_reset to tdo from other internal and external reset sources internal reset
323 7766f?avr?11/10 atmega16/32u4 the active states are: ? capture-dr: data in the idcode register is sampled into the boundary-scan chain. ? shift-dr: the idcode scan chain is shifted by the tck input. 26.4.3 sample_preload; 0x2 mandatory jtag instruction for pre-loading the output latches and taking a snap-shot of the input/output pins without affecting the system operation. however, the output latches are not connected to the pins. the boundary-scan chain is selected as data register. the active states are: ? capture-dr: data on the external pins are sampled into the boundary-scan chain. ? shift-dr: the boundary-scan chain is shifted by the tck input. ? update-dr: data from the boundary-scan chain is applied to the output latches. however, the output latches are not connected to the pins. 26.4.4 avr_reset; 0xc the avr specific public jtag instruction for forcing the avr device into the reset mode or releasing the jtag reset source. the tap controller is not reset by this in struction. the one bit reset register is selected as da ta register. note that the reset will be active as long as there is a logic ?one? in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr: the reset register is shifted by the tck input. 26.4.5 bypass; 0xf mandatory jtag instructio n selecting the bypass register for data register. the active states are: ? capture-dr: loads a logic ?0? into the bypass register. ? shift-dr: the bypass register cell between tdi and tdo is shifted. 26.5 boundary-scan related re gister in i/o memory 26.5.1 mcu control register ? mcucr the mcu control register contains control bits for general mcu functions. ? bits 7 ? jtd: jtag interface disable when this bit is zero, the jtag interface is ena bled if the jtagen fuse is programmed. if this bit is one, the jtag interface is disabled. in or der to avoid unintentional disabling or enabling of the jtag interface, a timed sequence must be followed when changing this bit: the application software must write this bit to the desired value twice within four cycles to change its value. note that this bit must not be altered when using the on-chip debug system. bit 76543210 jtd ? ? pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
324 7766f?avr?11/10 atmega16/32u4 26.5.2 mcu status register ? mcusr the mcu status register provides information on which reset source caused an mcu reset. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. 26.6 boundary-scan chain the boundary-scan chain has the capability of drivin g and observing the logi c levels on the digi- tal i/o pins, as well as the boundary between digi tal and analog logic for analog circuitry having off-chip connection. 26.6.1 scanning the digital port pins figure 26-3 shows the boundary-scan cell for a bi-dir ectional port pin. the pull-up function is disabled during boundary-scan when the jtag ic contains extest or sample_preload. the cell consists of a bi-directional pin cell that combines the three signals output control - ocxn, output data - odxn, and input data - idxn, into only a two-stage shift register. the port and pin indexes are not used in the following description the boundary-scan logic is not included in the figures in the datasheet. figure 26-4 shows a simple digital port pin as described in the section ?i/o-ports? on page 65 . the boundary-scan details from figure 26-3 replaces the dashed box in figure 26-4 . when no alternate port function is present, the input data - id - corresponds to the pinxn regis- ter value (but id has no synchronizer), output data corresponds to the port register, output control corresponds to the data direction - dd register, and the pull-up enable - puexn - cor- responds to logic expression pud ddxn portxn. digital alternate port functions are connected outside the dotted box in figure 26-4 to make the scan chain read the actual pin value. for analog f unction, there is a direct connection from the external pin to the analog circuit. there is no scan chain on the interface between the digital and the analog circuitry, but some digital control signal to analog circuitry are turned off to avoid driv- ing contention on the pads. when jtag ir contains extest or sample_preload the clock is not sent out on the port pins even if the ckout fuse is programmed. ev en though the clock is output when the jtag ir contains sample_preload, the clock is not sampled by the boundary scan. bit 76543210 ? ? ?jtrf wdrf borf extrf porf mcusr read/write r r r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description
325 7766f?avr?11/10 atmega16/32u4 figure 26-3. boundary-scan cell for bi-directional port pin with pull-up function. dq dq g 0 1 0 1 dq dq g 0 1 0 1 0 1 port pin (pxn) vcc extest to next cell shiftdr output control (oc) output data (od) input data (id) from last cell updatedr clockdr ff1 ld1 ld0 ff0 0 1 pull-up enable (pue)
326 7766f?avr?11/10 atmega16/32u4 figure 26-4. general port pin schematic diagram 26.6.2 scanning the reset pin the reset pin accepts 5v active low logic fo r standard reset operation, and 12v active high logic for high voltage parallel programming. an observe-only cell as shown in figure 26-5 is inserted for the 5v reset signal. figure 26-5. observe-only cell clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data bus sleep sleep: sleep control pxn i/o i/o see boundary-scan description for details! puexn ocxn odxn idxn puexn: pullup enable for pin pxn ocxn: output control for pin pxn odxn: output data to pin pxn idxn: input data from pin pxn 0 1 dq from previous cell clockdr shiftdr to next cell from system pin to system logic ff1
327 7766f?avr?11/10 atmega16/32u4 26.7 atmega16u4/atmega32u 4 boundary-scan order table 26-3 shows the scan order between tdi and tdo when the boundary-scan chain is selected as data path. bit 0 is the lsb; the first bit scanned in, and the first bit scanned out. the scan order follows the pin-out order as far as possible. exceptions from the rules are the scan chains for the analog circuits, which constitute th e most significant bits of the scan chain regard- less of which physical pin they are connected to. in figure 26-3 , pxn. data corresponds to ff0, pxn. control corresponds to ff1, pxn. bit 4, 5, 6 and 7 of port f is not in the scan chain, since these pins constitute the tap pins when the jt ag is enabled. the usb pads are not included in the boundary-scan. table 26-3. atmega16u4/atmega32u4 boundary-scan order bit number signal name module 88 pe6.data port e 87 pe6.control 86 reserved 85 reserved 84 reserved 83 reserved 82 pb0.data port b 81 pb0.control 80 pb1.data 79 pb1.control 78 pb2.data 77 pb2.control 76 pb3.data 75 pb3.control 74 pb4.data 73 pb4.control 72 pb5.data 71 pb5.control 70 pb6.data 69 pb6.control 68 pb7.data 67 pb7.control 66 reserved porte 65 reserved 64 reserved 63 reserved 62 rstt reset logic (observe only)
328 7766f?avr?11/10 atmega16/32u4 61 pd0.data port d 60 pd0.control 59 pd1.data 58 pd1.control 57 pd2.data 56 pd2.control 55 pd3.data 54 pd3.control 53 pd4.data 52 pd4.control 51 pd5.data 50 pd5.control 49 pd6.data 48 pd6.control 47 pd7.data 46 pd7.control 45 reserved port e 44 reserved 43 reserved 42 reserved 41 reserved reserved 40 reserved 39 reserved 38 reserved 37 reserved 36 reserved 35 reserved 34 reserved 33 reserved 32 reserved 31 reserved 30 reserved 29 reserved 28 reserved 27 reserved 26 reserved table 26-3. atmega16u4/atmega32u4 boundary-scan order (continued) bit number signal name module
329 7766f?avr?11/10 atmega16/32u4 26.8 boundary-scan description language files boundary-scan description language (bsdl) files describe boundary-scan capable devices in a standard format used by automated test-generation software. the order and function of bits in the boundary-scan data register are included in th is description. bsdl files are available for atmega16u4/atmega32u4. 25 pe2.data port e 24 pe2.control 23 reserved reserved 22 reserved 21 reserved 20 reserved 19 reserved 18 reserved 17 reserved 16 reserved 15 reserved 14 reserved 13 reserved 12 reserved 11 reserved 10 reserved 9 reserved 8 reserved 7 reserved port f 6 reserved 5 reserved 4 reserved 3pf1.data 2 pf1.control 1pf0.data 0 pf0.control table 26-3. atmega16u4/atmega32u4 boundary-scan order (continued) bit number signal name module
330 7766f?avr?11/10 atmega16/32u4 27. boot loader support ? read -while-write self-programming the boot loader support provides a real read- while-write self-programming mechanism for downloading and uploading program code by the m cu itself. this feature a llows flexible applica- tion software updates controlled by the mcu using a flash-resident boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program mem- ory. the program code within the boot loader section has the capability to write into the entire flash, including the boot loader memory. the b oot loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and t he boot loader has two separate sets of boot lock bits which can be set indepen dently. this gives the user a uniq ue flexibility to select differ- ent levels of protection. general information on spm and elpm is provided in see ?avr cpu core? on page 9. 27.1 boot loader features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficient algorithm ? efficient read-modify-write support note: 1. a page is a section in the flash consisting of several bytes (see table 28-11 on page 351 ) used during programming. the page organiz ation does not affect normal operation. 27.2 application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 27-2 ). the size of the different sections is configured by the bootsz fuses as shown in table 27-8 on page 344 and figure 27-2 . these two sections can have different level of protection since they have different sets of lock bits. 27.2.1 application section the application section is the section of the flash that is used for storing the application code. the protection level for the application section can be selected by the application boot lock bits (boot lock bits 0), see table 27-2 on page 334 . the application section can never store any boot loader code since the spm instruction is disabled when executed from the application section. 27.2.2 bls ? boot loader section while the application section is used for storing the application code, the the boot loader soft- ware must be located in the bls since the spm instruction can initiate a programming when executing from the bls only. the spm instruct ion can access the entire flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 27-3 on page 334 . 27.3 read-while-write and no r ead-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader soft- ware update is dependent on which address that is being programmed. in addition to the two
331 7766f?avr?11/10 atmega16/32u4 sections that are configurable by the bootsz fuses as described above, the flash is also divided into two fixed sections, the read-whi le-write (rww) section and the no read-while- write (nrww) section. the limit between the rww- and nrww sections is given in table 27- 1 and figure 27-1 on page 332 . the main difference between the two sections is: ? when erasing or writing a page located inside the rww section, the nrww section can be read during the operation. ? when erasing or writing a page located inside the nrww section, the cpu is halted during the entire operation. note that the user software can never read any code that is located inside the rww section dur- ing a boot loader software operation. the syntax ?read-while-write section? refers to which section that is being programmed (erased or written), not which section that actually is being read during a boot loader software update. 27.3.1 rww ? read-while-write section if a boot loader software update is programming a page inside the rww section, it is possible to read code from the flash, but only code that is located in the nrww section. during an on- going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (i.e., by load program memory, call, or jump instructions or an interrupt) during programming, the software might end up in an unknown state. to avoid this, the inte rrupts should either be disabled or moved to the boot loader section. the boot loader section is always located in the nrww section. the rww section busy bit (rwwsb) in the store program memory control and status register (spmcsr) will be read as logica l one as long as the rww sectio n is blocked for reading. after a programming is completed, the rwwsb must be cleared by software before reading code located in the rww section. see ?store program memory control and status register ? spmcsr? on page 336. for details on how to clear rwwsb. 27.3.2 nrww ? no read-while-write section the code located in the nrww section can be read when the boot loader software is updating a page in the rww section. when the boot loader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. table 27-1. read-while-write features which section does the z- pointer address during the programming? which section can be read during programming? is the cpu halted? read-while-write supported? rww section nrww section no yes nrww section none yes no
332 7766f?avr?11/10 atmega16/32u4 figure 27-1. read-while-write vs. no read-while-write read-while-write (rww) section no read-while-write (nrww) section z-pointer addresses rww section z-pointer addresses nrww section cpu is halted during the operation code located in nrww section can be read during the operation
333 7766f?avr?11/10 atmega16/32u4 figure 27-2. memory sections note: 1. the parameters in the figure above are given in table 27-8 on page 344 . 27.4 boot loader lock bits if no boot loader capability is n eeded, the entire flash is available for application code. the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to sele ct different levels of protection. the user can select: ? to protect the entire flash from a software update by the mcu. ? to protect only the boot loader flash section from a software update by the mcu. ? to protect only the application flash section from a software update by the mcu. ? allow software update in the entire flash. see table 27-2 and table 27-3 for further details. the boot lock bits can be set by software and in serial or in parallel programming mode. they can only be cleared by a chip erase command only. the general write lock (lock bit mode 2) does not control the programming of the flash memory by spm instruction. similarly, the general read/write lock (lock bit mode 1) does not control reading nor writing by (e )lpm/spm, if it is attempted. 0x0000 flashend program memory bootsz = '11' application flash section boot loader flash section flashend program memory bootsz = '10' 0x0000 program memory bootsz = '01' program memory bootsz = '00' application flash section boot loader flash section 0x0000 flashend application flash section flashend end rww start nrww application flash section boot loader flash section boot loader flash section end rww start nrww end rww start nrww 0x0000 end rww, end application start nrww, start boot loader application flash section application flash section application flash section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section end application start boot loader end application start boot loader end application start boot loader
334 7766f?avr?11/10 atmega16/32u4 note: 1. ?1? means unprogrammed, ?0? means programmed note: 1. ?1? means unprogrammed, ?0? means programmed 27.5 entering the b oot loader program the bootloader can be executed with three different conditions: 27.5.1 regular application conditions. a jump or call from the application program. this may be initiated by a trigger such as a com- mand received via usart, spi or usb. 27.5.2 boot reset fuse the boot reset fuse (bootrst) can be programmed so that the reset vector is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the application code is loaded, the program can start executing the application code. note that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse table 27-2. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 no restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 27-3. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 no restrictions for spm or (e)lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from t he application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section.
335 7766f?avr?11/10 atmega16/32u4 is programmed, the reset vector will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. note: 1. ?1? means unprogrammed, ?0? means programmed 27.5.3 external hardware conditions the hardware boot enable fuse (hwbe) can be programmed (see table 27-5 ) so that upon special hardware conditions under reset, the bootloader execution is forced after reset. note: 1. ?1? means unprogrammed, ?0? means programmed when the hwbe fuse is enable the ale/hwb pin is configured as input during reset and sam- pled during reset rising edge. when ale/hwb pin is ?0? during reset rising edge, the reset vector will be set as the boot loader re set address and the bo ot loader will be exec uted (see figures 27-3). figure 27-3. boot process description table 27-4. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset (see table 27-8 on page 344 ) table 27-5. hardware boot enable fuse (1) hwbe reset address 1ale/hwb pin can not be used to force boot loader execution after reset 0ale/hwb pin is used during reset to force bootloader execution after reset hwbe bootrst ? ext. hardware conditions ? reset vector = application reset reset vector =boot lhoader reset ? reset ale/hwb t shrh t hhrh
336 7766f?avr?11/10 atmega16/32u4 27.5.4 store program memory control and status register ? spmcsr the store program memory control and status register contains the control bits needed to con- trol the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the status register is set (one), the spm ready interrupt will be enabled. the spm ready in terrupt will be ex ecuted as long as the spmen bit in the spmcsr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operation to the rww section is initi- ated, the rwwsb will be set (one ) by hardware. when the rwws b bit is set, the rww section cannot be accessed. the rwwsb bit will be cleared if the rwwsre bit is written to one after a self-programming operation is completed. alter natively the rwwsb bit will automatically be cleared if a page load operation is initiated. ? bit 5 ? sigrd: signature row read if this bit is written to one at the same time as spmen, the next lpm instruction within three clock cycles will read a byte from the signatu re row into the dest ination register. see ?reading the signature row from software? on page 341 for details. an spm inst ruction within four cycles after sigrd and spmen are set will have no effect. this operation is reserved for future use and should not be used. ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by hardware). to re-enable the rww section, the user software must wait unt il the programming is complet ed (spmen will be cl eared). then, if the rwwsre bit is written to one at the same time as spmen, the next spm instruction within four clock cycles re-enables the rww secti on. the rww section cannot be re-enabled while the flash is busy with a page erase or a page wr ite (spmen is set). if the rwwsre bit is writ- ten while the flash is being loaded, the flas h load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles sets boot lock bits, according to the data in r0. the data in r1 and the address in the z- pointer are ignored. the blbset bit will autom atically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an (e)lpm instructio n within three cycles after blbset and spmen are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in th e z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 340 for details. bit 7 6 5 4 3 2 1 0 spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen spmcsr read/write r/w r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
337 7766f?avr?11/10 atmega16/32u4 ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page write, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon co mpletion of a page write, or if no spm instruction is ex ecuted within four clock cycles. the cpu is halted during the ent ire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bi t will auto-clear upon comp letion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either rwwsre, blbset, pgwrt? or pgers, t he following spm instruction will have a spe- cial meaning, see description abo ve. if only spmen is written, the following spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spmen bit will aut o-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. during page erase and page write, the spmen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011? or ?00001? in the lower five bits will have no effect. note: only one spm instruction should be active at any time. 27.6 addressing the flash during self-programming the z-pointer is used to address the spm commands. the z pointer consists of the z-registers zl and zh in the register file, and rampz in the i/o space. the number of bits actually used is implementation dependent. note that the rampz register is only implemented when the pro- gram space is larger than 64k bytes. since the flash is organized in pages (see table 28-11 on page 351 ), the program counter can be treated as having two different sections. one sect ion, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 27-4 . note that the page erase and page write operations are addressed independently. therefore it is of major importance that the boot loader software addresses the same page in both the page erase and page write operation. once a program- ming operation is initiated, the address is latched and the z-pointer can be used for other operations. the (e)lpm instruction use the z-pointer to st ore the address. since this instruction addresses the flash byte-by-byte, also bit z0 of the z-pointer is used. bit 2322212019181716 15 14 13 12 11 10 9 8 rampz rampz7 rampz6 rampz5 rampz4 rampz3 rampz2 rampz1 rampz0 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30)z7z6z5z4z3z2z1z0 76543210
338 7766f?avr?11/10 atmega16/32u4 figure 27-4. addressing the flash during spm (1) note: 1. the different variables used in figure 27-4 are listed in table 27-10 on page 345 . 27.7 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buf- fer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the bu ffer before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page write alternative 2, fill the bu ffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. when using alternative 1, the boot loader provides an effective read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alter- native 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same program memory 0 1 23 z - pointer bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word page pcword[pagemsb:0]: 00 01 02 pageend page pcword pcpage pcmsb pagemsb program counter
339 7766f?avr?11/10 atmega16/32u4 page. see ?simple assembly code example for a boot loader? on page 342 for an assembly code example. 27.7.1 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?x0000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation. ? page erase to the rww section: the nrww section can be read during the page erase. ? page erase to the nrww section: the cpu is halted during the operation. 27.7.2 filling the temporary buffer (page loading) to write an instruction word, set up the address in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the content of pcword in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page write operation or by writing the rwwsre bit in spmcsr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. 27.7.3 performing a page write to execute page write, set up the address in the z-pointer, write ?x0000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. ? page write to the rww section: the nrww section can be read during the page write. ? page write to the nrww section: the cpu is halted during the operation. 27.7.4 using the spm interrupt if the spm interrupt is en abled, the spm interrupt will genera te a constant in terrupt when the spmen bit in spmcsr is cleared. this means th at the interrupt can be used instead of polling the spmcsr register in software. when using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an interrupt is accessing the rww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 61 . 27.7.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to program the boot lock bit11 to protect the boot loader software from any internal software changes. 27.7.6 prevent reading the rww section during self-programming during self-programming (either page erase or page write), the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self programming operation. the rwwsb in the spmcsr will be set as long as the rww section is busy. during self-programming the interrupt vector table should be moved to the bls
340 7766f?avr?11/10 atmega16/32u4 as described in ?interrupts? on page 61 , or the interrupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see ?simple assembly code example for a boot loader? on page 342 for an example. 27.7.7 setting the boot loader lock bits by spm to set the boot loader lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the only accessible lock bits are the boot lock bits that may prevent the a pplication and boot loader section from any soft- ware update by the mcu. see table 27-2 and table 27-3 for how the different settings of the boot loader bits affect the flash access. if bits 5..2 in r0 are cleared (zero), the corresponding boot lock bit will be programmed if an spm instruction is executed within four cycles after blbset and spmen are set in spmcsr. the z-pointer is don?t ca re during this operation, but for fu ture compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lo ck bits). for future compatibility it is also recommended to set bits 7, 6, 1, and 0 in r0 to ?1? when writing the lock bits. when pro- gramming the lock bits the entire flash can be read during the operation. 27.7.8 eeprom write prevents writing to spmcsr note that an eeprom write oper ation will block all software progra mming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operation. it is recommended that the user checks the status bit (eepe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 27.7.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and spmen bits in spmcsr. when an (e)lpm instruction is executed within three cpu cycles after the blbset and spmen bits are set in spmcsr, the value of the lock bi ts will be loaded in the desti nation register. the blbset and spmen bits will auto-clear upon comple tion of reading the lock bits or if no (e)lpm instruction is executed within three cpu cycles or no spm instruction is executed within four cpu cycles. when blbset and spmen are cleared, (e)lpm will work as described in the instruction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and spmen bits in spmcsr. when an (e)lpm inst ruction is executed within three cycles after the blbset and spmen bits are set in the spmc sr, the value of the fuse low byte (flb) will be loaded in the destination register as shown below. refer to table 28-5 on page 348 for a detailed description and mapping of the fuse low byte. bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 1 1 bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 7654 3210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0
341 7766f?avr?11/10 atmega16/32u4 similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. when an (e)lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse high byte (fhb ) will be loaded in the destination register as shown below. refer to table 28-4 on page 348 for detailed description and mapping of the fuse high byte. when reading the extended fuse byte, load 0x0002 in the z-pointer. when an (e)lpm instruc- tion is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the exten ded fuse byte (efb) will be loaded in the destination r egister as shown below. refer to table 28-3 on page 347 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. 27.7.10 reading the signature row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 27-6 on page 341 and set the sigrd and spmen bits in spmcsr. when an lpm instruction is executed within three cpu cycles after the sigrd and spmen bits are set in spmcsr, the signature byte valu e will be loaded in the destin ation register. the sigrd and spmen bits will auto-clear upon completion of re ading the signature row lo ck bits or if no lpm instruction is executed within three cpu cycles. when sigrd and spmen are cl eared, lpm will work as described in the instruction set manual. note: all other addresses are reserved for future use. 27.7.11 preventing flash corruption during periods of low v cc , the flash program can be corrupted because the supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situ ations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate correctly. secondly, the cpu itself can execute instruct ions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): bit 7654 3210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0 bit 7654 3210 rd ? ? ? ? ? efb2 efb1 efb0 table 27-6. signature row addressing signature byte z-pointer address device signature byte 1 0x0000 device signature byte 2 0x0002 device signature byte 3 0x0004 rc oscillator calibration byte 0x0001
342 7766f?avr?11/10 atmega16/32u4 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr reset active (low) during peri ods of insufficient po wer supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will pre- vent the cpu from attempting to decode and execute instructions, effectively protecting the spmcsr register and thus the flash from unintentional writes. 27.7.12 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 27-7 shows the typical pro- gramming time for flash accesses from the cpu. 27.7.13 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 343 7766f?avr?11/10 atmega16/32u4 brne wrloop ; execute page write subi zl, low(pagesizeb) ;restore pointer sbci zh, high(pagesizeb) ;not required for pagesizeb<=256 ldi spmcrval, (1< 344 7766f?avr?11/10 atmega16/32u4 27.7.14 atmega16u4/atmega32u4 boot loader parameters in table 27-8 through table 27-10 , the parameters used in the description of the self-program- ming are given. note: 1. the different bootsz fuse configurations are shown in figure 27-2 note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 331 and ?rww ? read-while-write section? on page 331 . table 27-8. boot size configuration (word addresses) (1) device bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) atmega32u4 1 1 256 words 4 0x0000 - 0x3eff 0x3f00 - 0x3fff 0x3eff 0x3f00 1 0 512 words 8 0x0000 - 0x3dff 0x3e00 - 0x3fff 0x3dff 0x3e00 0 1 1024 words 16 0x0000 - 0x3bff 0x3c00 - 0x3fff 0x3bff 0x3c00 0 0 2048 words 32 0x0000 - 0x37ff 0x3800 - 0x3fff 0x37ff 0x3800 atmega16u4 1 1 256 words 4 0x0000 - 0x1eff 0x1f00 - 0x1fff 0x1eff 0x1f00 1 0 512 words 8 0x0000 - 0x1dff 0x1e00 - 0x1fff 0x1dff 0x1e00 0 1 1024 words 16 0x0000 - 0x1bff 0x1c00 - 0x1fff 0x1bff 0x1c00 0 0 2048 words 32 0x0000 - 0x17ff 0x1800 - 0x1fff 0x17ff 0x1800 table 27-9. read-while-write limit (word addresses) (1) device section pages address atmega32u4 read-while-write section (rww) 224 0x0000 - 0x37ff no read-while-write section (nrww) 32 0x3800 - 0x3fff atmega16u4 read-while-write section (rww) 97 0x0000 - 0x17ff no read-while-write section (nrww) 32 0x1800 - 0x1fff
345 7766f?avr?11/10 atmega16/32u4 note: 1. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. note: see ?addressing the flash during self-programming? on page 337 for details about the use of z- pointer during self-programming. table 27-10. explanation of different variables used in figure 27-4 and the mapping to the z- pointer variable corresponding z-value (1) description pcmsb 13 most significant bit in the program counter. (the program counter is 14 bits pc[13:0]) pag e m s b 6 most significant bit which is used to address the words within one page (64 words in a page requires six bits pc [5:0]). zpcmsb z14 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z7 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[13:6] z14:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation)
346 7766f?avr?11/10 atmega16/32u4 28. memory programming 28.1 program and data memory lock bits the atmega16u4/atmega32u4 provides six lock bits which can be left unprogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 28-2 . the lock bits can only be erased to ?1? with the chip erase command. note: 1. ?1?: unprogrammed, ?0?: programmed table 28-1. lock bit byte (1) lock bit byte bit no description default value atmega16u4/32u4 atmega16u4rc/32u4rc 7? 1 6? 1 blb12 5 boot lock bit 1 blb11 4 boot lock bit 0 1 blb02 3 boot lock bit 1 blb01 2 boot lock bit 1 lb2 1 lock bit 0 1 lb1 0 lock bit 0 1 table 28-2. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flas h and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parallel and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 111 no restrictions for spm or (e )lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrup ts are disabled while executing from the application section.
347 7766f?avr?11/10 atmega16/32u4 notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed 28.2 fuse bits the atmega16u4/atmega32u4 has three bytes. table 28-3 - table 28-5 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. note that the fuses are read as logical zero, ?0?, if they are programmed. notes: 1. see table 8-2 on page 52 for bodlevel fuse decoding. 2. ?1? means unprogrammed, ?0? means programmed blb1 mode blb12 blb11 111 no restrictions for spm or (e )lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the application section is not allowed to read from the boot loader section. if inte rrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the applic ation section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 28-2. lock bit protection modes (1)(2) (continued) memory lock bits protection type table 28-3. extended fuse byte (2) fuse low byte bit no description default value atmega16/32u4 atmega16/32u4rc ?7? 1 ?6? 1 ?5? 1 ?4? 1 hwbe 3 hardware boot enable 0 (programmed) 1 (unprogrammed) bodlevel2 (1) 2 brown-out detector tri gger level 0 (programmed) bodlevel1 (1) 1 brown-out detector trigger level 1 (unprogrammed) bodlevel0 (1) 0 brown-out detector trigger level 1 (unprogrammed)
348 7766f?avr?11/10 atmega16/32u4 note: 1. the spien fuse is not accessible in serial programming mode. 2. the default value of bootsz1..0 results in maximum boot size. see table 27-8 on page 344 for details. 3. see ?watchdog timer? on page 55 for details. 4. never ship a product with the ocden fuse prog rammed regardless of the setting of lock bits and jtagen fuse. a programmed ocden fuse en ables some parts of the clock system to be running in all sleep modes. this may increase the power consumption. note: 1. the default setting of cksel3..0 results in low power crystal oscillator for atmega16u4 and atmega32u4, and internal rc oscillator for atmega16u4rc and atmega32u4rc. see table 6-1 on page 28 for details. 2. the ckout fuse allow the system clock to be output on portc7. see ?clock output buffer? on page 37 for details. 3. see ?system clock prescaler? on page 37 for details. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. table 28-4. fuse high byte fuse high byte bit no description default value ocden (4) 7 enable ocd 1 (unprogrammed, ocd disabled) jtagen 6 enable jtag 0 (programmed, jtag enabled) spien (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) wdton (3) 4 watchdog timer always on 1 (unprogrammed) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom preserved) bootsz1 2 select boot size (see table 28-7 for details) 0 (programmed) (2) bootsz0 1 select boot size (see table 28-7 for details) 0 (programmed) (2) bootrst 0 select bootloader address as reset vector 1 (unprogrammed, reset vector @0x0000) table 28-5. fuse low byte fuse low byte bit nr description default value atmega16u4/32u4 atmega16u4rc/32u4rc ckdiv8 (3) 7 divide clock by 8 0 (programmed) ckout (2) 6 clock output 1 (unprogrammed) sut1 5 select start-up time 0 (programmed) sut0 4 select start-up time 1 (unprogrammed) cksel3 3 select clock source 1 (unprogrammed) (1) 0 (programmed) (1) cksel2 2 select clock source 1 (unprogrammed) (1) 0 (programmed) (1) cksel1 1 select clock source 1 (unprogrammed) (1) 1 (unprogrammed) (1) cksel0 0 select clock source 0 (programmed) (1) 0 (programmed) (1)
349 7766f?avr?11/10 atmega16/32u4 28.2.1 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuse s are also latched on power-up in normal mode. 28.3 signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. atmega16u4 signature bytes: 1. 0x000: 0x1e (indicates manufactured by atmel). 2. 0x001: 0x94 (indicates 16kb flash memory). 3. 0x002: 0x88 (indicates atmega16u4 device). atmega32u4 signature bytes: 1. 0x000: 0x1e (indicates manufactured by atmel). 2. 0x001: 0x95 (indicates 32kb flash memory). 3. 0x002: 0x87 (indicates atmega32u4 device). 28.4 calibration byte the atmega16u4/a tmega32u4 has a byte calib ration value for the inte rnal rc oscillator. this byte resides in the high byte of address 0x000 in the signature address space. during reset, this byte is automatically written into the osccal register to ensure correct frequency of the cali- brated rc oscillator. 28.5 parallel programming paramete rs, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bi ts in the atmega16u4/atmega32u4. pulses are assumed to be at least 250 ns unless otherwise noted. 28.5.1 signal names in this section, some pins of the atmega16u4/atmega32u4 are referenced by signal names describing their functionality during parallel programming, see figure 28-1 and table 28-6 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a positive pulse. the bit coding is shown in table 28-9 . when pulsing wr or oe , the command loaded determines the action executed. the different commands are shown in table 28-10 .
350 7766f?avr?11/10 atmega16/32u4 figure 28-1. parallel programming (1) note: 1. unused pins should be left floating. table 28-6. pin name mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming, 1: device is ready for new command. oe pd2 i output enable (active low). wr pd3 i write pulse (active low). bs1 pd4 i byte select 1. xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 pagel pd7 i program memory and eeprom data page load. bs2 pe6 i byte select 2. data pb7-0 i/o bi-directional data bus (output when oe is low). table 28-7. bs2 and bs1 encoding bs2 bs1 flash / eeprom address flash data loading / reading fuse programming reading fuse and lock bits 0 0 low byte low byte low byte fuse low byte 0 1 high byte high byte high byte lock bits 10 extended high byte reserved extended byte extended fuse byte 1 1 reserved reserved reserved fuse high byte vcc +5v gnd xtal1 pd1 pd2 pd3 pd4 pd5 pd6 pb7 - pb0 data reset pd7 +12 v bs1 xa0 xa1 oe rdy/bsy pagel pe6 wr bs2 avcc +5v
351 7766f?avr?11/10 atmega16/32u4 , table 28-8. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 28-9. xa1 and xa0 enoding xa1 xa0 action when xtal1 is pulsed 00 load flash or eeprom address (high or low address byte determined by bs2 and bs1). 0 1 load data (high or low data byte for flash determined by bs1). 1 0 load command 1 1 no action, idle table 28-10. command byte bit encoding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom table 28-11. no. of words in a page and no. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 16k words (32k bytes) 128 words pc[6:0] 128 pc[13:7] 13
352 7766f?avr?11/10 atmega16/32u4 28.6 parallel programming 28.6.1 enter programming mode the following algorithm puts the devi ce in parallel programming mode: 1. apply 4.5 - 5.5v between v cc and gnd. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 28-8 on page 351 to ?0000? and wait at least 100 ns. 4. apply 11.5 - 12.5v to reset . any activity on prog_enable pins within 100 ns after +12v has been applied to reset , will cause the device to fail entering programming mode. 5. wait at least 50 s before sending a new command. 28.6.2 considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations. ? skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and flash after a chip erase. ? address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom. this consideration also applies to signature bytes reading. 28.6.3 chip erase the chip erase will erase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be perfor med before the flas h and/or eeprom are reprogrammed. note: 1. the eeprpom memory is preserved during ch ip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this starts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command. table 28-12. no. of words in a page and no. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 1k bytes 8 bytes eea[2:0] 128 eea[9:3] 9
353 7766f?avr?11/10 atmega16/32u4 28.6.4 programming the flash the flash is organized in pages, see table 28-11 on page 351 . when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be pro- grammed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte (address bits 7..0) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?00?. this selects the address low byte. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 28-3 for signal waveforms) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash . this is illustrated in figure 28-2 on page 354 . note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte (address bits15..8) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?01?. this selects the address high byte. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. load address extended high byte (address bits 23..16) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?10?. this selects the address extended high byte.
354 7766f?avr?11/10 atmega16/32u4 3. set data = address extended high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. i. program page 1. set bs2, bs1 to ?00? 2. give wr a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low. 3. wait until rdy/bsy goes high (see figure 28-3 for signal waveforms). j. repeat b through i until the entire flash is programmed or until all data has been programmed. k. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. figure 28-2. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 28-11 on page 351 . program memory word address within a page page address within the flash instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
355 7766f?avr?11/10 atmega16/32u4 figure 28-3. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters refer to the programming description above. 28.6.5 programming the eeprom the eeprom is organized in pages, see table 28-12 on page 352 . when programming the eeprom, the program data is latche d into a page buffer. this al lows one page of data to be programmed simultaneously. th e programming algorithm for th e eeprom data memory is as follows (refer to ?programming the flash? on page 353 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page 1. set bs2, bs1 to ?00?. 2. give wr a negative pulse. this starts prog ramming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page (see figure 28-4 for signal waveforms). rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx abcdeb cdeg f addr. ext.h h i
356 7766f?avr?11/10 atmega16/32u4 figure 28-4. programming the eeprom waveforms 28.6.6 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 353 for details on command and address loading): 1. a: load command ?0000 0010?. 2. h: load address extended byte (0x00- 0xff). 3. g: load address high byte (0x00 - 0xff). 4. b: load address low byte (0x00 - 0xff). 5. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 6. set bs to ?1?. the flash word high byte can now be read at data. 7. set oe to ?1?. 28.6.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 353 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 28.6.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 353 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agbceb c el k
357 7766f?avr?11/10 atmega16/32u4 28.6.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 353 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs2, bs1 to ?01?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs2, bs1 to ?00?. this selects low data byte. 28.6.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?programming the flash? on page 353 for details on command and data loading): 1. 1. a: load command ?0100 0000?. 2. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. 3. set bs2, bs1 to ?10?. this selects extended data byte. 4. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. 5. set bs2, bs1 to ?00?. this selects low data byte. figure 28-5. programming the fuses waveforms 28.6.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 353 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is programmed (lb1 and lb2 is programmed), it is not possible to program the boot lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. rdy/bsy wr oe reset +12v pagel 0x40 data data xx xa1 xa0 bs1 xtal1 ac 0x40 data xx ac write fuse low byte write fuse high byte 0x40 data xx ac write extended fuse byte bs2
358 7766f?avr?11/10 atmega16/32u4 28.6.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 353 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, and bs2, bs1 to ?00?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, and bs2, bs1 to ?11?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, and bs2, bs1 to ?10?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, and bs2, bs1 to ?01?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. figure 28-6. mapping between bs1, bs2 and the fuse and lock bits during read 28.6.13 reading the signature bytes the algorithm for reading the signatur e bytes is as follows (refer to ?programming the flash? on page 353 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 28.6.14 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to ?programming the flash? on page 353 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. lock bits 0 1 bs2 fuse high byte 0 1 bs1 data fuse low byte 0 1 bs2 extended fuse byte
359 7766f?avr?11/10 atmega16/32u4 28.6.15 parallel programming characteristics figure 28-7. parallel programming timing, including some general timing requirements figure 28-8. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 28-7 (i.e., t dvxh , t xhxl , and t xldx ) also apply to load- ing operation. figure 28-9. parallel programming timing, reading sequence (within the same page) with timing requirements (1) data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte) xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
360 7766f?avr?11/10 atmega16/32u4 note: 1. the timing requirements shown in figure 28-7 (i.e., t dvxh , t xhxl , and t xldx ) also apply to read- ing operation. notes: 1. t wlrh is valid for the write flash, write eepro m, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. 28.7 serial downloading both the flash and eeprom memo ry arrays can be programmed using a serial programming bus while reset is pulled to gnd. the serial programming interface consists of pins sck, pdi (input) and pdo (output). after reset is set low, the programming enable instruction needs to be executed first before program/erase operations can be executed. note, in table 28-14 on page 361 , the pin mapping for serial programming is listed. not all packages use the spi pins dedicated for the internal serial peripheral interface - spi. table 28-13. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs2/1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/bsy low 0 1 s t wlrh wr low to rdy/bsy high (1) 3.7 4.5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns
361 7766f?avr?11/10 atmega16/32u4 28.8 serial programming pin mapping figure 28-10. serial programming and verify (1) notes: 1. if the device is clocked by the internal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < avcc < v cc + 0.3v, however, avcc should always be within 1.8 - 5.5v when programming the eeprom, an auto-erase cycle is built into the self-timed programming operation (in the serial mode only) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low: > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz high: > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz 28.8.1 serial programming algorithm when writing serial data to the atmega16u4/ atmega32u4, data is clocked on the rising edge of sck. when reading data from the at mega16u4/atmega32u4, data is clocked on the falling edge of sck. see figure 28-11 for timing details. to program and verify the atmega16u4/atmega32u4 in the serial programming mode, the fol- lowing sequence is recommended (see four byte instruction formats in table 28-16 ): table 28-14. pin mapping serial programming symbol pins (tqfp-64) i/o description pdi pb2 i serial data in pdo pb3 o serial data out sck pb1 i serial clock vcc gnd xtal1 sck pdo pdi reset +1.8 - 5.5v avcc +1.8 - 5.5v (2)
362 7766f?avr?11/10 atmega16/32u4 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in some sys- tems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. wait for at least 20 ms and enable serial programming by sending the programming enable serial instruction to pin pdi. 3. the serial programming instructions will no t work if the communic ation is out of syn- chronization. when in sync. the second byte (0x53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 7 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the program memory page is stored by loading the write program memory page instruction with the address lines 15..8. before issuing this command, make sure the instruction load extended address byte has been used to define the msb of the address. the extended address byte is stored until the command is re-issued, i.e., the command needs only be issued for the first page, and when crossi ng the 64kword boundary. if polling ( rdy/bsy ) is not used, the user must wait at least t wd_flash before issuing the next page. (see table 28- 15 .) accessing the serial programming interface before the flash write operation com- pletes can result in incorrect programming. 5. the eeprom array is programmed one byte at a time by supplying the address and data together with the appropriate write instruction. an eeprom memory location is first automatically erased before new data is written. if pollin g is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 28-15 .) in a chip erased device, no 0xffs in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output pdo. when reading the flash memory, use the instruction load extended address byte to define the upper address byte, which is not included in the read program memory instruction. the extended address byte is stored until the command is re-issued, i.e., the command needs only be issued for the first page, and when crossing the 64kword boundary. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v cc power off. table 28-15. minimum wait delay before writing the next flash or eeprom location symbol minimum wait delay t wd_flash 4.5 ms t wd_eeprom 9.0 ms t wd_erase 9.0 ms
363 7766f?avr?11/10 atmega16/32u4 figure 28-11. serial programming waveforms msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output
364 7766f?avr?11/10 atmega16/32u4 table 28-16. serial programming instruction set instruction instruction format operation byte 1 byte 2 byte 3 byte4 programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx enable serial programming after reset goes low. chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx chip erase eeprom and flash. load extended address byte 0100 1101 0000 0000 cccc cccc xxxx xxxx defines extended address byte for read program memory and write program memory page. read program memory 0010 h 000 aaaa aaaa bbbb bbbb oooo oooo read h (high or low) data o from program memory at word address c : a : b . load program memory page 0100 h 000 xxxx xxxx xx bb bbbb iiii iiii write h (high or low) data i to program memory page at word address b . data low byte must be loaded before data high byte is applied within the same address. write program memory page 0100 1100 aaaa aaaa bb xx xxxx xxxx xxxx write program memory page at address c : a : b . read eeprom memory 1010 0000 0000 aaaa bbbb bbbb oooo oooo read data o from eeprom memory at address a : b . write eeprom memory 1100 0000 0000 aaaa bbbb bbbb iiii iiii write data i to eeprom memory at address a : b . load eeprom memory page (page access) 1100 0001 0000 0000 0000 00 bb iiii iiii load data i to eeprom memory page buffer. after data is loaded, program eeprom page. write eeprom memory page (page access) 1100 0010 0000 aaaa bbbb bb00 xxxx xxxx write eeprom page at address a : b . read lock bits 0101 1000 0000 0000 xxxx xxxx xx oo oooo read lock bits. ?0? = programmed, ?1? = unprogrammed. see table 28-1 on page 346 for details. write lock bits 1010 1100 111x xxxx xxxx xxxx 11 ii iiii write lock bits. set bits = ?0? to program lock bits. see table 28-1 on page 346 for details. read signature byte 0011 0000 000x xxxx xxxx xx bb oooo oooo read signature byte o at address b . write fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write fuse high bits 1010 1100 1010 1000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write extended fuse bits 1010 1100 1010 0100 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 28-3 on page 347 for details. read fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo read fuse bits. ?0? = programmed, ?1? = unprogrammed. read fuse high bits 0101 1000 0000 1000 xxxx xxxx oooo oooo read fuse high bits. ?0? = pro- grammed, ?1? = unprogrammed.
365 7766f?avr?11/10 atmega16/32u4 note: a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care 28.8.2 serial programming characteristics for characteristics of the serial programming m odule see ?spi timing characteristics? on page 383. 28.9 programming via the jtag interface programming through the jtag interface requires control of the four jtag specific pins: tck, tms, tdi, and tdo. control of the reset and clock pins is not required. to be able to use the jtag interface, the jtagen fuse must be programmed. the device is default shipped with the fuse programmed. in addition, the jtd bit in mcucsr must be cleared. alternatively, if the jtd bit is set, the external reset can be fo rced low. then, the jtd bit will be cleared after two chip clocks, and the jtag pins are available for programming. this provides a means of using the jtag pins as normal port pi ns in running mode while still allowing in-sys- tem programming via the jtag interface. note th at this technique can not be used when using the jtag pins for boundary-scan or on-chip debug. in these cases the jtag pins must be ded- icated for this purpose. during programming the clock frequency of the tck input must be less than the maximum fre- quency of the chip. the system clock prescaler can not be used to divide the tck clock input into a sufficiently low frequency. as a definition in this datasheet, the lsb is shifted in and out first of all shift registers. 28.9.1 programming specific jtag instructions the instruction register is 4-bit wide, supporting up to 16 instructions. the jtag instructions useful for programming are listed below. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. the run-test/idle state of the tap controller is used to generate internal clocks. it can also be used as an idle state between jtag sequences . the state machine sequence for changing the instruction word is shown in figure 28-12 . read extended fuse bits 0101 0000 0000 1000 xxxx xxxx oooo oooo read extended fuse bits. ?0? = pro- grammed, ?1? = unprogrammed. see table 28-3 on page 347 for details. read calibration byte 0011 1000 000x xxxx 0000 0000 oooo oooo read calibration byte poll rdy/bsy 1111 0000 0000 0000 xxxx xxxx xxxx xxx o if o = ?1?, a programming operation is still busy. wait until this bit returns to ?0? before applying another command. table 28-16. serial programming instruction set (continued) instruction instruction format operation byte 1 byte 2 byte 3 byte4
366 7766f?avr?11/10 atmega16/32u4 figure 28-12. state machine sequence for changing the instruction word 28.9.2 avr_reset (0xc) the avr specific public jtag in struction for setting the avr device in the reset mode or taking the device out from the reset mode. the tap controller is not reset by this instruction. the one bit reset register is selected as data register. no te that the reset will be active as long as there is a logic ?one? in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr: the reset register is shifted by the tck input. 28.9.3 prog_enable (0x4) the avr specific public jtag instruction for enabling programming via the jtag port. the 16- bit programming enable register is selected as data register. the active states are the following: ? shift-dr: the programming enable signature is shifted into the data register. ? update-dr: the programming enable signature is compared to the correct value, and programming mode is entered if the signature is valid. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
367 7766f?avr?11/10 atmega16/32u4 28.9.4 prog_commands (0x5) the avr specific public jtag instruction for entering programming commands via the jtag port. the 15-bit programming command register is selected as data register. the active states are the following: ? capture-dr: the result of the previous command is loaded into the data register. ? shift-dr: the data register is shifted by the tck input, shifting out the result of the previous command and shifting in the new command. ? update-dr: the programming command is applied to the flash inputs ? run-test/idle: one clock cycle is generated, executing the applied command 28.9.5 prog_pageload (0x6) the avr specific public jtag instruction to directly load the flash data page via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? shift-dr: the flash data byte register is shifted by the tck input. ? update-dr: the content of the flash data byte register is copied into a temporary register. a write sequence is initiated that within 11 tck cycles loads the content of the temporary register into the flash page buffer. the avr automatically alternates between writing the low and the high byte for each new update-dr state, starting with the low byte for the first update-dr encountered after entering the prog_pageload command. the program counter is pre-incremented before writing the low byte, except for the first written byte. this ensures that the first data is written to the address set up by prog_commands, and loading the last location in the page buffer does not make the program counter increment into the next page. 28.9.6 prog_pageread (0x7) the avr specific public jtag instruction to dire ctly capture the flash content via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? capture-dr: the content of the selected flash byte is captured into the flash data byte register. the avr automatically alternates between reading the low and the high byte for each new capture-dr state, starting with the low byte for the first capture-dr encountered after entering the prog_pageread command. the program counter is post-incremented after reading each high byte, including the first r ead byte. this ensures that the first data is captured from the first address set up by prog_commands, and reading the last location in the page makes the program counter increment into the next page. ? shift-dr: the flash data byte register is shifted by the tck input. 28.9.7 data registers the data registers are selected by the jtag instruction registers described in section ?pro- gramming specific jtag instructions? on page 365 . the data registers relevant for programming operations are: ? reset register ? programming enable register ? programming command register ? flash data byte register
368 7766f?avr?11/10 atmega16/32u4 28.9.8 reset register the reset register is a test data register used to reset the part during programming. it is required to reset the part before entering programming mode. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high value present in t he reset register. depending on the fuse settings for the clock options, the part will remain reset for a re set time-out period (refer to ?clock sources? on page 28 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 8-1 on page 50 . 28.9.9 programming enable register the programming enable register is a 16-bit regist er. the contents of this register is compared to the programming enable signature, binary code 0b1010_0011_0111_0000. when the con- tents of the register is equal to the programming enable signature, programming via the jtag port is enabled. the register is reset to 0 on power-on reset, and should always be reset when leaving programming mode. figure 28-13. programming enable register 28.9.10 programming command register the programming command register is a 15-bit regist er. this register is us ed to serially shift in programming commands, and to serially shift out the result of the previous command, if any. the jtag programming instruction set is shown in table 28-17 . the state sequence when shifting in the programming comma nds is illustrated in figure 28-15 . tdi tdo d a t a = dq clockdr & prog_enable programming enable 0xa370
369 7766f?avr?11/10 atmega16/32u4 figure 28-14. programming command register tdi tdo s t r o b e s a d d r e s s / d a t a flash eeprom fuses lock bits
370 7766f?avr?11/10 atmega16/32u4 table 28-17. jtag programming instruction set a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes 1a. chip erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. poll for chip erase complete 0110011_10000000 xxxxx o x_xxxxxxxx (2) 2a. enter flash write 0100011_00010000 xxxxxxx_xxxxxxxx 2b. load address extended high byte 0001011_ cccccccc xxxxxxx_xxxxxxxx (10) 2c. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx 2d. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 2e. load data low byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 2f. load data high byte 0010111_ iiiiiiii xxxxxxx_xxxxxxxx 2g. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2h. write flash page 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2i. poll for page write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 3a. enter flash read 0100011_00000010 xxxxxxx_xxxxxxxx 3b. load address extended high byte 0001011_ cccccccc xxxxxxx_xxxxxxxx (10) 3c. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx 3d. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 3e. read data low and high byte 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo low byte high byte 4a. enter eeprom write 0100011_00010001 xxxxxxx_xxxxxxxx 4b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (10) 4c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 4d. load data byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 4e. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4f. write eeprom page 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1)
371 7766f?avr?11/10 atmega16/32u4 4g. poll for page write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 5a. enter eeprom read 0100011_00000011 xxxxxxx_xxxxxxxx 5b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (10) 5c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 5d. read data byte 0110011_ bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 6a. enter fuse write 0100011_01000000 xxxxxxx_xxxxxxxx 6b. load data low byte (6) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6c. write fuse extended byte 0111011_00000000 0111001_00000000 0111011_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6d. poll for fuse write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6e. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6f. write fuse high byte 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6g. poll for fuse write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6h. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6i. write fuse low byte 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6j. poll for fuse write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 7a. enter lock bit write 0100011_00100000 xxxxxxx_xxxxxxxx 7b. load data byte (9) 0010011_11 iiiiii xxxxxxx_xxxxxxxx (4) 7c. write lock bits 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 7d. poll for lock bit write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 8a. enter fuse/lock bit read 0100011_00000100 xxxxxxx_xxxxxxxx 8b. read extended fuse byte (6) 0111010_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8c. read fuse high byte (7) 0111110_00000000 0111111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo table 28-17. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes
372 7766f?avr?11/10 atmega16/32u4 notes: 1. this command sequence is not required if the seven msb are correctly set by the previous command sequence (which is normally the case). 2. repeat until o = ?1?. 3. set bits to ?0? to program the corresponding fuse, ?1? to unprogram the fuse. 4. set bits to ?0? to program the corresponding lock bit, ?1? to leave the lock bit unchanged. 5. ?0? = programmed, ?1? = unprogrammed. 6. the bit mapping for fuses extended byte is listed in table 28-3 on page 347 7. the bit mapping for fuses high byte is listed in table 28-4 on page 348 8. the bit mapping for fuses low byte is listed in table 28-5 on page 348 9. the bit mapping for lock bits byte is listed in table 28-1 on page 346 10. address bits exceeding pcmsb and eeamsb ( table 28-11 and table 28-12 ) are don?t care 11. all tdi and tdo sequences are represented by binary digits (0b...). 8d. read fuse low byte (8) 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8e. read lock bits (9) 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xx oooooo (5) 8f. read fuses and lock bits 0111010_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo (5) fuse ext. byte fuse high byte fuse low byte lock bits 9a. enter signature byte read 0100011_00001000 xxxxxxx_xxxxxxxx 9b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 9c. read signature byte 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 10a. enter calibration byte read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 10c. read calibration byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 11a. load no operation command 0100011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx table 28-17. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes
373 7766f?avr?11/10 atmega16/32u4 figure 28-15. state machine sequence for changing/reading the data word 28.9.11 flash data byte register the flash data byte register provides an ef ficient way to load the entire flash page buffer before executing page write, or to read out/verify the content of the flash. a state machine sets up the control signals to the flash and senses the strobe signals from the flash, thus only the data words need to be shifted in/out. the flash data byte register actually consists of the 8-bit scan chain and a 8-bit temporary reg- ister. during page load, the update-dr state copies the content of the scan chain over to the temporary register and initiates a write sequence that within 11 tck cycles loads the content of the temporary register into the flash page bu ffer. the avr automatically alternates between writing the low and the high byte for each new update-dr state, starting with the low byte for the first update-dr encountered after entering the prog_pageload command. the program counter is pre-incremented before writing the low byte, except for the first written byte. this ensures that the first data is written to the address set up by prog_commands, and loading the last location in the page buffer does not make the program counter increment into the next page. during page read, the content of the selected flash byte is captured into the flash data byte register during the capture-dr state. the avr automatically alternates between reading the low and the high byte for each new capture-dr state, starting with the low byte for the first cap- test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
374 7766f?avr?11/10 atmega16/32u4 ture-dr encountered after entering the prog_pageread command. the program counter is post-incremented after reading each high byte, including the first read byte. this ensures that the first data is captured from the first ad dress set up by prog_commands, and reading the last location in the page makes the program counter increment into the next page. figure 28-16. flash data byte register the state machine controlling the flash data by te register is clocked by tck. during normal operation in which eight bits are shifted for eac h flash byte, the clock cycles needed to navigate through the tap controller automatically feeds the state machine for the flash data byte regis- ter with sufficient number of clock pulses to complete its operation transparently for the user. however, if too few bits are shifted between each update-dr state during page load, the tap controller should stay in the run-test/idle state for some tck cycles to ensure that there are at least 11 tck cycles between each update-dr state. 28.9.12 programming algorithm all references below of type ?1a?, ?1b?, and so on, refer to table 28-17 . 28.9.13 entering programming mode 1. enter jtag instruction avr_reset and shift 1 in the reset register. 2. enter instruction prog_enable and shift 0b1010_0011_0111_0000 in the program- ming enable register. 28.9.14 leaving programming mode 1. enter jtag instruction prog_commands. 2. disable all programming instructions by using no operation instruction 11a. 3. enter instruction prog_enable and shift 0b0000_0000_0000_0000 in the program- ming enable register. 4. enter jtag instruction avr_reset and shift 0 in the reset register. tdi tdo d a t a flash eeprom fuses lock bits strobes address state machine
375 7766f?avr?11/10 atmega16/32u4 28.9.15 performing chip erase 1. enter jtag instruction prog_commands. 2. start chip erase using programming instruction 1a. 3. poll for chip erase complete using prog ramming instruction 1b, or wait for t wlrh_ce (refer to table 28-13 on page 360 ). 28.9.16 programming the flash before programming the flash a chip erase must be performed, see ?performing chip erase? on page 375. 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load address extended high byte using programming instruction 2b. 4. load address high byte using programming instruction 2c. 5. load address low byte using programming instruction 2d. 6. load data using programming instructions 2e, 2f and 2g. 7. repeat steps 5 and 6 for all instruction words in the page. 8. write the page using programming instruction 2h. 9. poll for flash write complete using prog ramming instruction 2i, or wait for t wlrh (refer to table 28-13 on page 360 ). 10. repeat steps 3 to 9 until all data have been programmed. a more efficient data transfer can be achieved using the prog_pageload instruction: 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load the page address using programming instructions 2b, 2c and 2d. pcword (refer to table 28-11 on page 351 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageload. 5. load the entire page by shifting in all instruction words in the page byte-by-byte, start- ing with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. use update-dr to copy the contents of the flash data byte register into the flash page location and to auto-increment the program counter before each new word. 6. enter jtag instruction prog_commands. 7. write the page using programming instruction 2h. 8. poll for flash write complete using prog ramming instruction 2i, or wait for t wlrh (refer to table 28-13 on page 360 ). 9. repeat steps 3 to 8 until all data have been programmed. 28.9.17 reading the flash 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load address using programming instructions 3b, 3c and 3d. 4. read data using programming instruction 3e. 5. repeat steps 3 and 4 until all data have been read. a more efficient data transfer can be ac hieved using the prog_pageread instruction:
376 7766f?avr?11/10 atmega16/32u4 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load the page address using programming instructions 3b, 3c and 3d. pcword (refer to table 28-11 on page 351 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageread. 5. read the entire page (or flash) by shifting out all instruction words in the page (or flash), starting with the lsb of the first instruction in the page (flash) and ending with the msb of the last instruction in the page (flash). the capture-dr state both captures the data from the flash, and also auto-increments the program counter after each word is read. note that capture-dr comes before the shift-dr state. hence, the first byte which is shifted out contains valid data. 6. enter jtag instruction prog_commands. 7. repeat steps 3 to 6 until all data have been read. 28.9.18 programming the eeprom before programming the eeprom a chip erase must be per formed, see ?performing chip erase? on page 375. 1. enter jtag instruction prog_commands. 2. enable eeprom write using programming instruction 4a. 3. load address high byte using programming instruction 4b. 4. load address low byte using programming instruction 4c. 5. load data using programming instructions 4d and 4e. 6. repeat steps 4 and 5 for all data bytes in the page. 7. write the data using programming instruction 4f. 8. poll for eeprom write complete using programming instruction 4g, or wait for t wlrh (refer to table 28-13 on page 360 ). 9. repeat steps 3 to 8 until all data have been programmed. note that the prog_ pageload instruction can not be us ed when program ming the eeprom. 28.9.19 reading the eeprom 1. enter jtag instruction prog_commands. 2. enable eeprom read using programming instruction 5a. 3. load address using programming instructions 5b and 5c. 4. read data using programming instruction 5d. 5. repeat steps 3 and 4 until all data have been read. note that the prog_pageread instructio n can not be used when reading the eeprom. 28.9.20 programming the fuses 1. enter jtag instruction prog_commands. 2. enable fuse write using programming instruction 6a. 3. load data high byte using programming instructions 6b. a bit value of ?0? will program the corresponding fuse, a ?1? will unprogram the fuse. 4. write fuse high byte using programming instruction 6c. 5. poll for fuse write complete using prog ramming instruction 6d, or wait for t wlrh (refer to table 28-13 on page 360 ).
377 7766f?avr?11/10 atmega16/32u4 6. load data low byte using pr ogramming instructions 6e. a ?0? will program the fuse, a ?1? will unprogram the fuse. 7. write fuse low byte using programming instruction 6f. 8. poll for fuse write complete using prog ramming instruction 6g, or wait for t wlrh (refer to table 28-13 on page 360 ). 28.9.21 programming the lock bits 1. enter jtag instruction prog_commands. 2. enable lock bit write usin g programming instruction 7a. 3. load data using programming instructions 7b. a bit value of ?0? will program the corre- sponding lock bit, a ?1? will leave the lock bit unchanged. 4. write lock bits using programming instruction 7c. 5. poll for lock bit write complete using programming instruction 7d, or wait for t wlrh (refer to table 28-13 on page 360 ). 28.9.22 reading the fuses and lock bits 1. enter jtag instruction prog_commands. 2. enable fuse/lock bit read using programming instruction 8a. 3. to read all fuses and lock bits, use programming instruction 8e. to only read fuse high byte, use programming instruction 8b. to only read fuse low byte, use programming instruction 8c. to only read lock bits, use programming instruction 8d. 28.9.23 reading the signature bytes 1. enter jtag instruction prog_commands. 2. enable signature byte read using programming instruction 9a. 3. load address 0x00 using programming instruction 9b. 4. read first signature byte us ing programming instruction 9c. 5. repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third signature bytes, respectively. 28.9.24 reading the calibration byte 1. enter jtag instruction prog_commands. 2. enable calibration byte read using programming instruction 10a. 3. load address 0x00 using programming instruction 10b. 4. read the calibration byte using programming instruction 10c.
378 7766f?avr?11/10 atmega16/32u4 29. electrical characteristics 29.1 absolute maximum ratings* 29.2 dc characteristics operating temperature.................................... -40 c to +85 c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of th is specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on any pin except reset and vbus with respect to ground (8) .............................-0.5v to v cc +0.5v voltage on reset with respect to ground......-0.5v to +13.0v voltage on vbus with respect to ground..........-0.5v to +6.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ............................................... 40.0 ma dc current v cc and gnd pins................................ 200.0 ma t a = -40 c to 85 c, v cc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min. (5) typ. max. (5) units v il input low voltage,except xtal1 and reset pin v cc = 2.7v - 5.5v -0.5 0.2v cc - 0.1v (1) (lvttl) v v il1 input low voltage, xtal1 pin v cc = 2.7v - 5.5v -0.5 0.1v cc (1) v v il2 input low voltage, reset pin v cc = 2.7v - 5.5v -0.5 0.1v cc (1) v v ih input high voltage, except xtal1 and reset pins v cc = 2.7v - 5.5v 0.2v cc +0.9v ( 2) (lvttl) v cc + 0.5 v v ih1 input high voltage, xtal1 pin v cc = 2.7v - 5.5v 0.7v cc (2) v cc + 0.5 v v ih2 input high voltage, reset pin v cc = 2.7v - 5.5v 0.9v cc (2) v cc + 0.5 v v ol output low voltage (3) , i ol = 10ma, v cc = 5v i ol = 5ma, v cc = 3v 0.7 0.5 v v oh output high voltage (4) , i oh = -10ma, v cc = 5v i oh = -5ma, v cc = 3v 4.2 2.3 v i il input leakage current i/o pin v cc = 5.5v, pin low (absolute value) 1a i ih input leakage current i/o pin v cc = 5.5v, pin high (absolute value) 1a r rst reset pull-up resistor 30 60 k r pu i/o pin pull-up resistor 20 50 k
379 7766f?avr?11/10 atmega16/32u4 note: 1. "max" means the highest value where the pin is guaranteed to be read as low 2. "min" means the lowest value where the pin is guaranteed to be read as high 3. although each i/o port can sink more than the test conditi ons (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), th e following must be observed: atmega16u4/atmega32u4: 1.)the sum of all iol, for ports a0-a7, g2, c4-c7 should not exceed 100 ma. 2.)the sum of all iol, for ports c0-c3, g0-g1, d0-d7 should not exceed 100 ma. 3.)the sum of all iol, for ports g3-g5, b0-b7, e0-e7 should not exceed 100 ma. 4.)the sum of all iol, for ports f0-f7 should not exceed 100 ma. if iol exceeds the test condition, vol may exceed the related sp ecification. pins are not guar anteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test co nditions (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), the following must be observed: atmega16u4/atmega32u4: 1)the sum of all ioh, for ports a0-a7, g2, c4-c7 should not exceed 100 ma. 2)the sum of all ioh, for ports c0-c3, g0-g1, d0-d7 should not exceed 100 ma. 3)the sum of all ioh, for ports g3-g5, b0-b7, e0-e7 should not exceed 100 ma. 4)the sum of all ioh, for ports f0-f7 should not exceed 100 ma. 5. all dc characteristics contained in this datasheet are based on simulation and characterization of other avr microcon- trollers manufactured in the same process technology. these values are preliminary values representing design targets, and will be updated after characterization of actual silicon 6. values with ?power reduction register 1 - prr1? disabled (0x00). i cc power supply current (6) active 4mhz, v cc = 3v (atmega16u4/atmega32u4) 5ma active 8mhz, v cc = 5v (atmega16u4/atmega32u4) 10 15 ma idle 4mhz, v cc = 3v (atmega16u4/atmega32u4) 2ma idle 8mhz, v cc = 5v (atmega16u4/atmega32u4) 6ma power-down mode wdt enabled, v cc = 3v, regulator disabled <10 12 a wdt disabled, v cc = 3v,regulator disabled 15a v acio analog comparator input offset voltage v cc = 5v v in = v cc /2 <10 40 mv i aclk analog comparator input leakage current v cc = 5v v in = v cc /2 -50 50 na t acid analog comparator propagation delay v cc = 2.7v v cc = 4.0v 750 500 ns rusb usb series resistor (external) 225% vreg regulator output voltage c ucap = 1f20%, uvcc 4.0v, i 80ma (7) , or uvcc 3.4v, i 55ma (7) 3.0 3.3 3.6 v t a = -40 c to 85 c, v cc = 2.7v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min. (5) typ. max. (5) units
380 7766f?avr?11/10 atmega16/32u4 7. maximum regulator output current should be reduced by the usb buffer current required when usb is active (about 25ma). the remaining regulator out put current can be used fo r the external application. 8. as specified on the usb electrical chapter, the d+/d- pads can withstand voltages down to -1v applied through a 39 ohms resistor 29.3 external clock drive waveforms figure 29-1. external clock drive waveforms 29.4 external clock drive note: all dc characteristics contained in this datasheet are based on simulation and characterization of other avr microcontrollers manufactured in the same process technology. these values are pre- liminary values representing design targets, and w ill be updated after characterization of actual silicon. 29.5 maximum speed vs. v cc maximum frequency is depending on v cc. as shown in figure 29-2 , the maximum frequency vs. v cc curve is linear between 2.7v < v cc < 5.5v. v il1 v ih1 table 29-1. external clock drive symbol parameter v cc =1.8-5.5v v cc =2.7-5.5v v cc =4.5-5.5v units min. max. min. max. min. max. 1/t clcl oscillator frequency 0208016mhz t clcl clock period 500 125 62.5 ns t chcx high time 200 50 25 ns t clcx low time 200 50 25 ns t clch rise time 2.0 1.6 0.5 s t chcl fall time 2.0 1.6 0.5 s t clcl change in period from one clock cycle to the next 22 2%
381 7766f?avr?11/10 atmega16/32u4 figure 29-2. maximum frequency vs. v cc , atmega16u4/atmega32u4 29.6 2-wire serial inte rface characteristics table 29-2 describes the requirements for devices connected to the 2-wire serial bus. the atmega16u4/atmega32u4 2- wire serial interface meets or exceeds thes e requirements under the noted conditions. timing symbols refer to figure 29-3 . 2.7 v 4.5 v 5.5 v safe operating area 16 mhz 8 mhz table 29-2. 2-wire serial bus requirements symbol parameter condition min max units vil input low-voltage -0.5 0.3 v cc v vih input high-voltage 0.7 v cc v cc + 0.5 v vhys (1) hysteresis of schmitt trigger inputs 0.05 v cc (2) ?v vol (1) output low-voltage 3 ma sink current 0 0.4 v tr (1) rise time for both sda and scl 20 + 0.1c b (3)(2) 300 ns tof (1) output fall time from v ihmin to v ilmax 10 pf < c b < 400 pf (3) 20 + 0.1c b (3)(2) 250 ns tsp (1) spikes suppressed by input filter 0 50 (2) ns i i input current each i/o pin 0.1v cc < v i < 0.9v cc -10 10 a c i (1) capacitance for each i/o pin ? 10 pf f scl scl clock frequency f ck (4) > max(16f scl , 250khz) (5) 0 400 khz rp value of pull-up resistor f scl 100 khz f scl > 100 khz t hd;sta hold time (repeated) start condition f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t low low period of the scl clock f scl 100 khz (6) 4.7 ? s f scl > 100 khz (7) 1.3 ? s v cc 0,4v ? 3ma ---------------------------- 1000ns c b ------------------- v cc 0,4v ? 3ma ---------------------------- 300ns c b --------------- -
382 7766f?avr?11/10 atmega16/32u4 notes: 1. in atmega16u4/atmega32u4, this parameter is characterized and not 100% tested. 2. required only for f scl > 100 khz. 3. c b = capacitance of one bus line in pf. 4. f ck = cpu clock frequency 5. this requirement applies to all atmega16u4/atmega32u4 2-wire serial interface operation. ot her devices connected to the 2-wire serial bus need only obey the general f scl requirement. 6. the actual low period generated by the atmeg a16u4/atmega32u4 2-wire serial interface is (1/f scl - 2/f ck ), thus f ck must be greater than 6 mhz for the low time r equirement to be strictly met at f scl = 100 khz. 7. the actual low period generated by the atmeg a16u4/atmega32u4 2-wire serial interface is (1/f scl - 2/f ck ), thus the low time requirement will not be strictly met for f scl > 308 khz when f ck = 8 mhz. still, atmega16u4/atmega32u4 devices con- nected to the bus may communicate at full speed (400 khz) with other atmega16u4/atmega32u4 devices, as well as any other device with a proper t low acceptance margin. figure 29-3. 2-wire serial bus timing t high high period of the scl clock f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t su;sta set-up time for a repeated start condition f scl 100 khz 4.7 ? s f scl > 100 khz 0.6 ? s t hd;dat data hold time f scl 100 khz 0 3.45 s f scl > 100 khz 0 0.9 s t su;dat data setup time f scl 100 khz 250 ? ns f scl > 100 khz 100 ? ns t su;sto setup time for stop condition f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t buf bus free time between a stop and start condition f scl 100 khz 4.7 ? s f scl > 100 khz 1.3 ? s table 29-2. 2-wire serial bus requirements (continued) symbol parameter condition min max units t su;sta t low t high t low t of t hd;sta t hd;dat t su;dat t su;sto t buf scl sda t r
383 7766f?avr?11/10 atmega16/32u4 29.7 spi timing characteristics see figure 29-4 and figure 29-5 for details. note: 1. in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12 mhz - 3 t clcl for f ck > 12 mhz figure 29-4. spi interface timing requirements (master mode) table 29-3. spi timing parameters description mode min typ max 1 sck period master see table 17-4 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master tbd 4 setup master 10 5holdmaster 10 6 out to sck master 0.5 ? t sck 7 sck to out master 10 8 sck to out high master 10 9ss low to out slave 15 10 sck period slave 4 ? t ck 11 sck high/low (1) slave 2 ? t ck 12 rise/fall time slave tbd 13 setup slave 10 14 hold slave t ck 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 20 mo si (data output) sck (cpol = 1) mi so (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 61 22 3 45 8 7
384 7766f?avr?11/10 atmega16/32u4 figure 29-5. spi interface timing requirements (slave mode) 29.8 hardware boot entr ancetiming characteristics figure 29-6. hardware boot timing requirements mi so (data output) sck (cpol = 1) mo si (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 10 11 11 12 13 14 17 15 9 x 16 table 29-4. hardware boot timings symbol parameter min max tshrh hwb low setup before reset high 0 thhrh hwb low hold after reset high startuptime( sut) + time out delay(tout) reset ale/hwb t shrh t hhrh table 29-5. adc characteristics symbol parameter condition min typ max units resolution single ended conversion 10 bits differential conversion, gain = 1x/10x/40x 8 differential conversion, gain = 200x 8 tue absolute accuracy v ref = 4v, v cc = 4v, adc clock = 200 khz 2.0 3.0 lsb gain = 1x/10x/40x, v ref = 4v, v cc = 5v, adc clock = 200 khz 2.0 3.0 gain = 200x, v ref = 4v, v cc = 5v, adc clock = 200 khz 2.0 4.0
385 7766f?avr?11/10 atmega16/32u4 inl integral non-linearity v ref = 4v, v cc = 4v, adc clock = 200 khz 0.5 1.5 lsb gain = 1x/10x/40x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.3 1.5 gain = 200x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.5 1.5 dnl differential non-linearity v ref = 4v, v cc = 4v, adc clock = 200 khz 0.4 0.7 lsb gain = 1x/10x/40x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.3 1.0 gain = 200x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.6 1.0 gain error v ref = 4v, v cc = 4v,adc clock = 200 khz -2.5 -1.0 2.5 lsb gain = 1x/10x/40x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.0 -1.5 -2.5 gain = 200x, v ref = 4v, v cc = 5v, adc clock = 200 khz 0.0 -1.8 -3.0 offset error v ref = 4v, v cc = 4v, adc clock = 200 khz -2.5 1.5 2.5 lsb v ref = 4v, v cc = 5v, adc clock = 200 khz, differential mode -2.0 0.0 2.0 v ref reference voltage single ended conversion 2.56 avcc v differential conversion 2.56 avcc - 0.5 avcc analog supply voltage v cc - 0.3 v cc + 0.3 v v in input voltage single ended channels gnd v ref v differential conversion 0 avcc input bandwidth single ended channels 38.5 khz differential channels 4 v int internal voltage reference 2.56v 2.4 2.56 2.8 v r ref reference input resistance 32 k r ain analog input resistance 100 m table 29-5. adc characteristics symbol parameter condition min typ max units
386 7766f?avr?11/10 atmega16/32u4 30. typical characteristics the following charts show typical behavior. t hese figures are not tested during manufacturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail-to-rail output is used as clock source. all active- and idle current consumption measurem ents are done with all bits in the prr regis- ters set and thus, the corresponding i/o modules are turned off. also the analog comparator is disabled during these measurements. see ?power reduction register? on page 45 for details. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient tempera- ture. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l * v cc *f wherec l = load capacitance, v cc = operating voltage and f = average switching frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the differential cur- rent drawn by the watchdog timer. 30.1 active supply current figure 30-1. active supply current vs. low frequency (1mhz) and t= 25c 5.5 v 5.0 v 4.5 v 4.0 v 3.6 v 2.7 v 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 1.6 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma)
387 7766f?avr?11/10 atmega16/32u4 figure 30-2. active supply current vs. low frequency (1mhz) and t= 85c figure 30-3. active supply current vs. frequency (1-16 mhz) and t= -40c 5.5 v 5.0 v 4.5 v 4.0 v 3.6 v 2.7 v 0.7 0.9 1.1 1.3 1.5 1.7 1.9 2.1 2.3 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma) 0 2 4 6 8 10 12 14 16 1 8 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 2.7 v 3.6 v 4.0 v 5.0 v 4.5 v
388 7766f?avr?11/10 atmega16/32u4 figure 30-4. active supply current vs. frequency (1-16 mhz) and t = 25c figure 30-5. active supply current vs. frequency (1-16 mhz) and t = 85c 0 2 4 6 8 10 12 14 16 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 5.0 v 4.5 v 2.7 v 3.6 v 4.0 v 0 2 4 6 8 10 12 14 16 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 2.7 v 3.6 v 4.0 v 5.0 v 4.5 v
389 7766f?avr?11/10 atmega16/32u4 30.2 idle supply current figure 30-6. idle supply current vs. low frequency (1 mhz) and t = 25c figure 30-7. idle supply current vs. low frequency (1 mhz) and t = 85c 5.5 v 5.0 v 4.5 v 4.0 v 3.6 v 2.7 v 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma) 5.5 v 5.0 v 4.5 v 4.0 v 3.6 v 2.7 v 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma)
390 7766f?avr?11/10 atmega16/32u4 figure 30-8. idle supply current vs. frequency (1-16 mhz) t = 25c figure 30-9. idle supply current vs. frequency (1-16 mhz) t = 85c 0 1 2 3 4 5 6 7 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 2.7 v 3.6 v 4.0 v 5.0 v 4.5 v 3.3 v 0 1 2 3 4 5 6 7 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 5.0 v 4.5 v 2.7 v 3.6 v 4.0 v
391 7766f?avr?11/10 atmega16/32u4 30.3 power-down supply current figure 30-10. power-down supply current vs. v cc (wdt disabled) figure 30-11. power-down supply current vs. v cc (wdt enabled) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) i cc ( u a) 8 5 c 25 c -40 c 4 6 8 10 12 14 16 1 8 20 22 24 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) i cc ( u a)
392 7766f?avr?11/10 atmega16/32u4 figure 30-12. power-down supply current vs. v cc (wdt enabled, bod en) 30.4 power-save supply current figure 30-13. power-save supply current vs. v cc (wdt disabled ) 8 5 c 25 c -40 c 21 24 27 30 33 36 39 42 45 4 8 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) i cc ( u a) 8 5 c 25 c -40 c 50 65 8 0 95 110 125 140 155 170 1 8 5 200 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) i cc ( u a)
393 7766f?avr?11/10 atmega16/32u4 30.5 pin pull-up figure 30-14. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7 v) figure 30-15. i/o pin pull-up resistor current vs. input voltage (v cc = 5 v) 0 10 20 30 40 50 60 70 8 0 0 0.5 1 1.5 2 2.5 3 v op ( v ) i op ( u a) 8 5 c 25 c -40 c 0 20 40 60 8 0 100 120 140 012345 v op ( v ) i op ( u a) 8 5 c 25 c -40 c
394 7766f?avr?11/10 atmega16/32u4 figure 30-16. reset pull-up resistor curr ent vs. reset pin voltage (v cc =5v) 30.6 pin driver strength figure 30-17. i/o pin output voltage vs. sink current (v cc = 3 v) 8 5 c 25 c 0 20 40 60 8 0 100 120 012345 v reset ( v ) i reset ( u a) -40 c 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 0246 8 10 12 14 16 1 8 20 i ol (ma) v ol ( v )
395 7766f?avr?11/10 atmega16/32u4 figure 30-18. i/o pin output voltage vs. sink current (v cc = 5 v) figure 30-19. i/o pin output voltage vs. source current (vcc = 3 v) 8 5 c 25 c -40 c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 0246 8 10 12 14 16 1 8 20 i ol (ma) v ol ( v ) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 0246 8 10 12 14 16 1 8 20 i oh (ma) v oh ( v )
396 7766f?avr?11/10 atmega16/32u4 figure 30-20. i/o pin output voltage vs. source current (v cc = 5 v) figure 30-21. usb dp lo pull-up resistor current vs. usb pin voltage 8 5 c 25 c -40 c 3.9 4.1 4.3 4.5 4.7 4.9 5.1 0246 8 10 12 14 16 1 8 20 i oh (ma) v oh ( v ) 8 5 c 25 c -40 c 0 400 8 00 1200 1600 2000 2400 2 8 00 0 0.5 1 1.5 2 2.5 3 3.5 v usb ( v ) i usb ( u a)
397 7766f?avr?11/10 atmega16/32u4 30.7 pin threshold and hysteresis figure 30-22. i/o pin input threshold voltage vs. v cc (v ih , io pin read as ?1?) figure 30-23. i/o pin input threshold voltage vs. v cc (v il , io pin read as ?0?) 8 5 c 25 c -40 c 0.6 0. 8 1 1.2 1.4 1.6 1. 8 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) threshold ( v ) 8 5 c 25 c -40 c 0.6 0. 8 1 1.2 1.4 1.6 1. 8 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) threshold ( v )
398 7766f?avr?11/10 atmega16/32u4 figure 30-24. usb pin input threshold voltage vs. v cc (v ih , io pin read as ?1? ) figure 30-25. usb pin input threshold voltage vs. v cc (v il , i/o pin read as ?0?) 8 5 c 25 c -40 c 1.2 1.3 1.4 1.5 1.6 1.7 1. 8 1.9 2 2.7 2. 8 2.9 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3. 8 v cc ( v ) threshold ( v ) 8 5 c 25 c -40 c 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 2.7 2. 8 2.9 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3. 8 v cc ( v ) threshold ( v )
399 7766f?avr?11/10 atmega16/32u4 figure 30-26. vbus pin input threshold voltage vs. v cc (v ih , io pin read as ?1?) figure 30-27. vbus pin input threshold voltage vs. v cc (v il , i/o pin read as ?0?) 8 5 c 25 c -40 c 4.3 8 4.4 4.42 4.44 4.46 4.4 8 4.5 4.52 4.54 4.56 4.5 8 4.6 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) threshold ( v ) 8 5 c 25 c -40 c 1.46 1.47 1.4 8 1.49 1.5 1.51 1.52 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) threshold ( v )
400 7766f?avr?11/10 atmega16/32u4 30.8 bod threshold figure 30-28. bod thresholds vs. temper ature (bodlevel is 2.6 v) figure 30-29. bod thresholds vs. temper ature (bodlevel is 3.5 v) rising v cc falling v cc 2.64 2.66 2.6 8 2.7 2.72 2.74 2.76 2.7 8 2. 8 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) threshold ( v ) rising v cc falling v cc 3.45 3.49 3.53 3.57 3.61 3.65 3.69 3.73 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) threshold ( v )
401 7766f?avr?11/10 atmega16/32u4 figure 30-30. bod thresholds vs. temper ature (bodlevel is 4.3 v) figure 30-31. bandgap voltage vs. vcc rising v cc falling v cc 4.1 4.15 4.2 4.25 4.3 4.35 4.4 4.45 4.5 4.55 4.6 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) threshold ( v ) 8 5 c 25 c -40 c 1.05 1.06 1.07 1.0 8 1.09 1.1 1.11 1.522.533.544.555.5 v cc ( v ) bandgap v oltage ( v )
402 7766f?avr?11/10 atmega16/32u4 figure 30-32. bandgap voltage vs. temperature 30.9 internal oscilllator speed figure 30-33. watchdog oscillator freq uency vs. temperature 4.5 v 3.0 v 1.9 v 5.0 v 5.5 v 1.05 1.06 1.07 1.0 8 1.09 1.1 1.11 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) bandgap v oltage ( v ) 5.5 v 4.5 v 4.0 v 3.0 v 1.9 v 112 114 116 11 8 120 122 124 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) f rc (khz)
403 7766f?avr?11/10 atmega16/32u4 figure 30-34. watchdog oscillato r frequency vs. v cc figure 30-35. calibrated 8 mhz rc oscillato r frequency vs. osccal value 8 5 c 25 c -40 c 110 112 114 116 11 8 120 122 124 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) f rc (khz) 8 5 c 25 c -40 c 0 2 4 6 8 10 12 14 016324 8 64 8 0 96 112 12 8 144 160 176 192 20 8 224 240 256 osccal (x1) f rc (mhz)
404 7766f?avr?11/10 atmega16/32u4 figure 30-36. calibrated 8 mhz rc oscillato r frequency vs. temperature figure 30-37. calibrated 8 mhz rc oscillator frequency vs. operating voltage 5.5 v 4.0 v 2.7 v 7.7 7. 8 7.9 8 8 .1 8 .2 8 .3 8 .4 -40 -30 -20 -10 0 10 20 30 40 50 60 70 8 090 temperat u re (c) f rc (mhz) 8 5 c 25 c -40 c 7.6 7.7 7. 8 7.9 8 8 .1 8 .2 8 .3 8 .4 2.5 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) f rc (mhz)
405 7766f?avr?11/10 atmega16/32u4 figure 30-38. osccal value step size in % (base frequency = 0.0 mhz) 30.10 current consumpti on of peripheral units figure 30-39. usb regulator level vs. v cc 8 5 c 25 c -40 c 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 0 16324 8 64 8 0 96 112 12 8 144 160 176 192 20 8 224 240 256 osccal (x1) f rc change ( % ) 8 5 c 25 c -40 c 2.7 2. 8 2.9 3 3.1 3.2 3.3 3.4 3.5 2.7 2.9 3.1 3.3 3.5 3.7 3.9 4.1 4.3 4.5 4.7 4.9 5.1 5.3 5.5 v cc ( v ) i cc ( u a)
406 7766f?avr?11/10 atmega16/32u4 figure 30-40. usb regulator level with load 75 vs. v cc figure 30-41. adc internal vref vs. vcc 8 5 c 25 c -40 c 2.5 2.6 2.7 2. 8 2.9 3 3.1 3.2 3.3 3.4 2. 8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc ( v ) c u rrent ( a) 8 5 c 25 c -40 c 2.45 2.46 2.47 2.4 8 2.49 2.5 2.51 2.52 2.53 2.54 2.6 2.9 3.2 3.5 3. 8 4.1 4.4 4.7 5 5.3 5.6 v oltage ( v ) v oltage v intref ( v )
407 7766f?avr?11/10 atmega16/32u4 figure 30-42. internal reference voltage vs. sink current 30.11 current consumption in reset and reset pulsewidth figure 30-43. reset supply current vs. frequency (1 - 20 mhz) 8 5 c 25 c -40 c 2.43 2.44 2.45 2.46 2.47 2.4 8 2.49 2.5 2.51 2.52 -7 -6 -5 -4 -3 -2 -1 0 sink c u rrent (ma) v oltage v intref ( v ) 0 0.5 1 1.5 2 2.5 3 3.5 246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 5.5 v 5.0 v 4.5 v 2.7 v 3.6 v 4.0 v
408 7766f?avr?11/10 atmega16/32u4 31. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0xff) reserved - - - - - - - - (0xfe) reserved - - - - - - - - (0xfd) reserved - - - - - - - - (0xfc) reserved - - - - - - - - (0xfb) reserved - - - - - - - - (0xfa) reserved - - - - - - - - (0xf9) reserved - - - - (0xf8) reserved - - - - - - - - (0xf7) reserved - - - - - - - - (0xf6) reserved - - - - - - - - (0xf5) reserved - - - - - - - - (0xf4) ueint - epint6:0 (0xf3) uebchx - - - - -byct10:8 (0xf2) uebclx byct7:0 (0xf1) uedatx dat7:0 (0xf0) ueienx flerre nakine - nakoute rxstpe rxoute stallede txine (0xef) uesta1x - - - - - ctrldir currbk1:0 (0xee) uesta0x cfgok overfi underfi - dtseq1:0 nbusybk1:0 (0xed) uecfg1x epsize2:0 epbk1:0 alloc - (0xec) uecfg0x eptype1:0 - - - - - epdir (0xeb) ueconx - - stallrq stallrqc rstdt - - epen (0xea) uerst - eprst6:0 (0xe9) uenum - - - - - epnum2:0 (0xe8) ueintx fifocon nakini rwal na kouti rxstpi rxouti stalledi txini (0xe7) reserved - - - - (0xe6) udmfn - - - fncerr - - - - (0xe5) udfnumh - - - - - fnum10:8 (0xe4) udfnuml fnum7:0 (0xe3) udaddr adden uadd6:0 (0xe2) udien - uprsme eorsme wakeupe eorste sofe msofe suspe (0xe1) udint - uprsmi eorsmi wakeupi eorsti sofi msofi suspi (0xe0) udcon - - - - rstcpu lsm rmwkup detach (0xdf) reserved (0xde) reserved (0xdd) reserved (0xdc) reserved (0xdb) reserved (0xda) usbint - - - - - - - vbusti (0xd9) usbsta - - - - - -idvbus (0xd8) usbcon usbe - frzclk otgpade - - - vbuste (0xd7) uhwcon - - - - - - - uvrege (0xd6) reserved (0xd5) reserved (0xd4) dt4 dt4h3 dt4h2 dt4h1 dt4h0 dt4l3 dt4l2 dt4l1 dt4l0 (0xd3) reserved (0xd2) ocr4d timer/counter4 - output compare register d (0xd1) ocr4c timer/counter4 - output compare register c (0xd0) ocr4b timer/counter4 - output compare register b (0xcf) ocr4a timer/counter4 - output compare register a (0xce) udr1 usart1 i/o data register (0xcd) ubrr1h - - - - usart1 baud rate register high byte (0xcc) ubrr1l usart1 baud rate register low byte (0xcb) reserved - - - - - - - - (0xca) ucsr1c umsel11 umsel10 upm1 1 upm10 usbs1 ucsz11 ucsz10 ucpol1 (0xc9) ucsr1b rxcie1 txcie1 udrie 1 rxen1 txen1 ucsz12 rxb81 txb81 (0xc8) ucsr1a rxc1 txc1 udre1 fe1 dor1 pe1 u2x1 mpcm1 (0xc7) clksta - - - - - - rcon exton (0xc6) clksel1 rccksel3 rcc ksel2 rccksel1 rcckse l0 excksel3 exc ksel2 excksel1 excksel0 (0xc5) clksel0 rcsut1 rcsut0 exsut1 exsut0 rce exte -clks (0xc4) tccr4e tlock4 enhc4 oc4oe5 oc4oe4 oc4oe3 oc4oe2 oc4oe1 oc4oe0 (0xc3) tccr4d fpie4 fpen4 fpnc4 fpes4 fpac4 fpf4 wgm41 wgm40 (0xc2) tccr4c com4a1s com4a0s com4b1s com4b0s com4d1s com4d0s foc4d pwm4d (0xc1) tccr4b pwm4x psr4 dtps41 dtps40 cs43 cs42 cs41 cs40 (0xc0) tccr4a com4a1 com4a0 com4b1 com4b0 foc4a foc4b pwm4a pwm4b (0xbf) tc4h - - - - - timer/counter4 high byte
409 7766f?avr?11/10 atmega16/32u4 (0xbe) tcnt4 timer/counter4 - counter register low byte (0xbd) twamr twam6 twam5 twam4 twam3 twam2 twam1 twam0 - (0xbc) twcr twint twea twsta twsto twwc twen -twie (0xbb) twdr 2-wire serial interface data register (0xba) twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce (0xb9) twsr tws7 tw s6 tws5 tws4 tws3 - twps1 twps0 (0xb8) twbr 2-wire serial interface bit rate register (0xb7) reserved - - - - - - - - (0xb6) reserved - (0xb5) reserved - - - - - - - - (0xb4) reserved - - - - - - - - (0xb3) reserved - - - - - - - - (0xb2) reserved - - - - - - - - (0xb1) reserved - - - - - - - - (0xb0) reserved - - - - - - - - (0xaf) reserved - - - - - - - - (0xae) reserved - - - - - - - - (0xad) reserved - - - - - - - - (0xac) reserved - - - - - - - - (0xab) reserved - - - - - - - - (0xaa) reserved - - - - - - - - (0xa9) reserved - - - - - - - - (0xa8) reserved - - - - - - - - (0xa7) reserved - - - - - - - - (0xa6) reserved - - - - - - - - (0xa5) reserved - - - - - - - - (0xa4) reserved - - - - - - - - (0xa3) reserved - - - - - - - - (0xa2) reserved - - - - - - - - (0xa1) reserved - - - - - - - - (0xa0) reserved - - - - - - - - (0x9f) reserved - - - - - - - - (0x9e) reserved - - - - - - - - (0x9d) ocr3ch timer/counter3 - output compare register c high byte (0x9c) ocr3cl timer/counter3 - output compare register c low byte (0x9b) ocr3bh timer/counter3 - output compare register b high byte (0x9a) ocr3bl timer/counter3 - output compare register b low byte (0x99) ocr3ah timer/counter3 - output compare register a high byte (0x98) ocr3al timer/counter3 - output compare register a low byte (0x97) icr3h timer/counter3 - input capture register high byte (0x96) icr3l timer/counter3 - input capture register low byte (0x95) tcnt3h timer/counter3 - counter register high byte (0x94) tcnt3l timer/counter3 - counter register low byte (0x93) reserved - - - - - - - - (0x92) tccr3c foc3a - - - - - - - (0x91) tccr3b icnc3 ices3 - wgm33 wgm32 cs32 cs31 cs30 (0x90) tccr3a com3a1 com3a0 com3b1 com3b0 com3c1 com3c0 wgm31 wgm30 (0x8f) reserved - - - - - - - - (0x8e) reserved - - - - - - - - (0x8d) ocr1ch timer/counter1 - output compare register c high byte (0x8c) ocr1cl timer/counter1 - output compare register c low byte (0x8b) ocr1bh timer/counter1 - output compare register b high byte (0x8a) ocr1bl timer/counter1 - output compare register b low byte (0x89) ocr1ah timer/counter1 - output compare register a high byte (0x88) ocr1al timer/counter1 - output compare register a low byte (0x87) icr1h timer/counter1 - input capture register high byte (0x86) icr1l timer/counter1 - input capture register low byte (0x85) tcnt1h timer/counter1 - counter register high byte (0x84) tcnt1l timer/counter1 - counter register low byte (0x83) reserved - - - - - - - - (0x82) tccr1c foc1a foc1b foc1c - - - - - (0x81) tccr1b icnc1 ices1 - wgm13 wgm12 cs12 cs11 cs10 (0x80) tccr1a com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 (0x7f) didr1 - - - - - - - ain0d (0x7e) didr0 adc7d adc6d adc5d adc4d - - adc1d adc0d (0x7d) didr2 - - adc13d adc12d adc11d adc10d adc9d adc8d address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
410 7766f?avr?11/10 atmega16/32u4 (0x7c) admux refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 (0x7b) adcsrb adhsm acme mux5 - adts3 adts2 adts1 adts0 (0x7a) adcsra aden adsc adate adif adie adps2 adps1 adps0 (0x79) adch adc data register high byte (0x78) adcl adc data register low byte (0x77) reserved - - - - - - - - (0x76) reserved - - - - - - - - (0x75) reserved - - - - - - - - (0x74) reserved - - - - - - - - (0x73) reserved - - - - - - - - (0x72) timsk4 ocie4d ocie4a ocie4b - - toie4 - - (0x71) timsk3 - - icie3 - ocie3c ocie3b ocie3a toie3 (0x70) reserved - - - - - - - - (0x6f) timsk1 - - icie1 - ocie1c ocie1b ocie1a toie1 (0x6e) timsk0 - - - - - ocie0b ocie0a toie0 (0x6d) reserved - - - - - - - - (0x6c) reserved - - - - - - - - (0x6b) pcmsk0 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 (0x6a) eicrb - -isc61isc60 - - - - (0x69) eicra isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 (0x68) pcicr - - - - - - -pcie0 (0x67) rcctrl - - - - - - - rcfreq (0x66) osccal rc oscillator calibration register (0x65) prr1 prusb - - prtim4 prtim3 - - prusart1 (0x64) prr0 prtwi - prtim0 - prtim1 prspi - pradc (0x63) reserved - - - - - - - - (0x62) reserved - - - - - - - - (0x61) clkpr clkpce - - - clkps3 clkps2 clkps1 clkps0 (0x60) wdtcsr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 0x3f (0x5f) sreg i t h s v n z c 0x3e (0x5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 0x3c (0x5c) reserved - - - - - - - - 0x3b (0x5b) rampz - - - - - - rampz1 rampz0 0x3a (0x5a) reserved - - - - - - - - 0x39 (0x59) reserved - - - - - - - - 0x38 (0x58) reserved - - - - - - - - 0x37 (0x57) spmcsr spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen 0x36 (0x56) reserved - - - - - - - - 0x35 (0x55) mcucr jtd - - pud - - ivsel ivce 0x34 (0x54) mcusr - - usbrf jtrf wdrf borf extrf porf 0x33 (0x53) smcr - - - - sm2 sm1 sm0 se 0x32 (0x52) pllfrq pinmux pllusb plltm1 plltm0 pdiv3 pdiv2 pdiv1 pdiv0 0x31 (0x51) ocdr/ mondr ocdr7 ocdr6 ocdr5 ocdr4 ocdr3 ocdr2 ocdr1 ocdr0 monitor data register 0x30 (0x50) acsr acd acbg aco aci acie acic acis1 acis0 0x2f (0x4f) reserved - - - - - - - - 0x2e (0x4e) spdr spi data register 0x2d (0x4d) spsr spif wcol - - - - - spi2x 0x2c (0x4c) spcr spie spe dord mstr cpol cpha spr1 spr0 0x2b (0x4b) gpior2 general purpose i/o register 2 0x2a (0x4a) gpior1 general purpose i/o register 1 0x29 (0x49) pllcsr - - - pindiv - -plleplock 0x28 (0x48) ocr0b timer/counter0 output compare register b 0x27 (0x47) ocr0a timer/counter0 output compare register a 0x26 (0x46) tcnt0 timer/counter0 (8 bit) 0x25 (0x45) tccr0b foc0a foc0b - - wgm02 cs02 cs01 cs00 0x24 (0x44) tccr0a com0a1 com0a0 com0b1 com0b0 - -wgm01wgm00 0x23 (0x43) gtccr tsm - - - - - psrasy psrsync 0x22 (0x42) eearh - - - - eeprom address register high byte 0x21 (0x41) eearl eeprom address register low byte 0x20 (0x40) eedr eeprom data register 0x1f (0x3f) eecr - - eepm1 eepm0 eerie eempe eepe eere 0x1e (0x3e) gpior0 general purpose i/o register 0 0x1d (0x3d) eimsk - int6 - - int3 int2 int1 int0 0x1c (0x3c) eifr - intf6 - - intf3 intf2 intf1 intf0 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
411 7766f?avr?11/10 atmega16/32u4 note: 1. for compatibility with future devices, reserved bits shoul d be written to zero if accessed. reserved i/o memory addresse s should never be written. 2. i/o registers within the address range $00 - $1f are directly bit-accessible using th e sbi and cbi instructions. in these reg - isters, the value of single bits can be checked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag read as set, thus clearing the flag. the cbi and sbi instruction s work with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses $00 - $3f must be used. when addressing i/o regis- ters as data space using ld and st instructions, $20 must be added to these addresses. the atmega16u4/atmega32u4 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the ex tended i/o space from $60 - $1ff in sram , only the st/sts/std and ld/lds/ldd instructions can be used. 0x1b (0x3b) pcifr - - - - - - -pcif0 0x1a (0x3a) reserved - - - - - - - - 0x19 (0x39) tifr4 ocf4d ocf4a ocf4b - -tov4 - - 0x18 (0x38) tifr3 - - icf3 - ocf3c ocf3b ocf3a tov3 0x17 (0x37) reserved - - - - - - - - 0x16 (0x36) tifr1 - - icf1 - ocf1c ocf1b ocf1a tov1 0x15 (0x35) tifr0 - - - - - ocf0b ocf0a tov0 0x14 (0x34) reserved - - - - - - - - 0x13 (0x33) reserved - - - - - - - - 0x12 (0x32) reserved - - - - - - - - 0x11 (0x31) portf portf7 portf6 portf5 portf4 - - portf1 portf0 0x10 (0x30) ddrf ddf7 ddf6 ddf5 ddf4 - - ddf1 ddf0 0x0f (0x2f) pinf pinf7 pinf6 pinf5 pinf4 - - pinf1 pinf0 0x0e (0x2e) porte - porte6 - - - porte2 - - 0x0d (0x2d) ddre - dde6 - - - dde2 - - 0x0c (0x2c) pine - pine6 - - - pine2 - - 0x0b (0x2b) portd portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 0x0a (0x2a) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 0x09 (0x29) pind pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 0x08 (0x28) portc portc7 portc6 - - - - - - 0x07 (0x27) ddrc ddc7 ddc6 - - - - - - 0x06 (0x26) pinc pinc7 pinc6 - - - - - - 0x05 (0x25) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 0x04 (0x24) ddrb ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 0x03 (0x23) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 0x02 (0x22) reserved - - - - - - - - 0x01 (0x21) reserved - - - - - - - - 0x00 (0x20) reserved - - - - - - - - address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
412 7766f?avr?11/10 atmega16/32u4 32. instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd rd ? rr z,n,v 1 andi rd, k logical and register and constant rd rd ? k z,n,v 1 or rd, rr logical or registers rd rd v rr z,n,v 1 ori rd, k logical or register and constant rd rd v k z,n,v 1 eor rd, rr exclusive or registers rd rd rr z,n,v 1 com rd one?s complement rd 0xff ? rd z,c,n,v 1 neg rd two?s complement rd 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 dec rd decrement rd rd ? 1 z,n,v 1 tst rd test for zero or minus rd rd ? rd z,n,v 1 clr rd clear register rd rd rd z,n,v 1 ser rd set register rd 0xff none 1 mul rd, rr multiply unsigned r1:r0 rd x rr z,c 2 muls rd, rr multiply signed r1:r0 rd x rr z,c 2 mulsu rd, rr multiply signed with unsigned r1:r0 rd x rr z,c 2 fmul rd, rr fractional multiply unsigned r1:r0 (rd x rr) << 1 z,c 2 fmuls rd, rr fractional multiply signed r1:r0 (rd x rr) << 1 z,c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 (rd x rr) << 1 z,c 2 branch instructions rjmp k relative jump pc pc + k + 1 none 2 ijmp indirect jump to (z) pc z none 2 eijmp extended indirect jump to (z) pc (eind:z) none 2 jmp k direct jump pc knone3 rcall k relative subroutine call pc pc + k + 1 none 4 icall indirect call to (z) pc znone4 eicall extended indirect call to (z) pc (eind:z) none 4 call k direct subroutine call pc knone5 ret subroutine return pc stack none 5 reti interrupt return pc stack i 5 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 none 1/2/3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 none 1/2/3 sbrs rr, b skip if bit in regi ster is set if (rr(b)=1) pc pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1/2
413 7766f?avr?11/10 atmega16/32u4 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1/2 brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 none 1/2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 none 1/2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) 1none2 cbi p,b clear bit in i/o register i/o(p,b) 0none2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z,c,n,v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z,c,n,v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) rd(7..4),rd(7..4) rd(3..0) none 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) tnone1 sec set carry c 1c1 clc clear carry c 0 c 1 sen set negative flag n 1n1 cln clear negative flag n 0 n 1 sez set zero flag z 1z1 clz clear zero flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 sev set twos complement overflow. v 1v1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1t1 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1h1 clh clear half carry flag in sreg h 0 h 1 data transfer instructions mov rd, rr move between registers rd rr none 1 movw rd, rr copy register word rd+1:rd rr+1:rr none 1 ldi rd, k load immediate rd knone1 ld rd, x load indirect rd (x) none 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 none 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) none 2 ld rd, y load indirect rd (y) none 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 none 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) none 2 ldd rd,y+q load indirect with displacement rd (y + q) none 2 ld rd, z load indirect rd (z) none 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 none 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) none 2 ldd rd, z+q load indirect with displacement rd (z + q) none 2 lds rd, k load direct from sram rd (k) none 2 st x, rr store indirect (x) rr none 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 none 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr none 2 st y, rr store indirect (y) rr none 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 none 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr none 2 std y+q,rr store indirect with displacement (y + q) rr none 2 st z, rr store indirect (z) rr none 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 none 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr none 2 std z+q,rr store indirect with displacement (z + q) rr none 2 sts k, rr store direct to sram (k) rr none 2 lpm load program memory r0 (z) none 3 lpm rd, z load program memory rd (z) none 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 none 3 elpm extended load program memory r0 (rampz:z) none 3 elpm rd, z extended load program memory rd (z) none 3 elpm rd, z+ extended load program memory rd (rampz:z), rampz:z rampz:z+1 none 3 mnemonics operands description operation flags #clocks
414 7766f?avr?11/10 atmega16/32u4 spm store program memory (z) r1:r0 none - in rd, p in port rd pnone1 out p, rr out port p rr none 1 push rr push register on stack stack rr none 2 pop rd pop register from stack rd stack none 2 mcu control instructions nop no operation none 1 sleep sleep (see specific description for sleep function) none 1 wdr watchdog reset (see specific description for wdr/timer) none 1 break break for on-chip debug only none n/a mnemonics operands description operation flags #clocks
415 7766f?avr?11/10 atmega16/32u4 33. ordering information 33.1 atmega16u4 speed (mhz) power supply ordering code default oscillator package operation range 16 2.7 - 5.5v atmega16u4-au external xtal 44ml industrial (-40 to +85c) atmega16u4rc-au internal calib. rc atmega16u4-mu external xtal 44pw atmega16u4rc-mu internal calib. rc package type 44ml ml, 44 - lead, 10 x 10 mm body size, 1.0 mm body thickness 0.8 mm lead pitch, thin profile plastic quad flat package (tqfp) 44pw pw, 44 - lead 7.0 x 7.0 mm body, 0.50 mm pitch quad flat no lead package (qfn)
416 7766f?avr?11/10 atmega16/32u4 33.2 atmega32u4 speed (mhz) power supply ordering code default oscillator package operation range 16 2.7 - 5.5 v atmega32u4-au external xtal 44ml industrial (-40 to +85c) atmega32u4rc-au internal calib. rc atmega32u4-mu external xtal 44pw atmega32u4rc-mu internal calib. rc package type 44ml ml, 44 - lead, 10 x 10 mm body size, 1.0 mm body thickness 0.8 mm lead pitch, thin profile plastic quad flat package (tqfp) 44pw pw, 44 - lead 7.0 x 7.0 mm body, 0.50 mm pitch quad flat no lead package (qfn)
417 7766f?avr?11/10 atmega16/32u4 34. packaging information 34.1 tqfp44
418 7766f?avr?11/10 atmega16/32u4 34.2 qfn44
419 7766f?avr?11/10 atmega16/32u4 35. errata the revision letter in this section refers to the revision of the atmega16u4/atmega32u4 device. 35.1 atmega16u4/atmega32u4 rev e ? spike on twi pins when twi is enabled ? high current consumption in sleep mode ? msb of ocr4a/b/d is write only in 11-bits enhanced pwm mode 1. spike on twi pins when twi is enabled 100 ns negative spike occurs on sda and scl pins when twi is enabled. problem fix/work around enable atmega16u4/atmega32u4 twi before the other nodes of the twi network. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected mode, the current consump- tion will increase during sleep when executing the sleep instruction directly after a sei instruction. problem fix/work around before entering sleep, interrupts not used to wake up the part from the sleep mode should be disabled. 3. msb of ocr4a/b/d is write only in 11-bits enhanced pwm mode in the 11-bits enhanced pwm mode the msb of ocr4a/b/d is write only. a read of ocr4a/b/d will always return zero in the msb position. problem fix/work around none. 35.2 atmega16u4/atmega32u4 rev d ? spike on twi pins when twi is enabled ? high current consumption in sleep mode ? timer 4 11-bits enhanced pwm mode 1. spike on twi pins when twi is enabled 100 ns negative spike occurs on sda and scl pins when twi is enabled. problem fix/work around enable atmega16u4/atmega32u4 twi before the other nodes of the twi network. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected mode, the current consump- tion will increase during sleep when executing the sleep instruction directly after a sei instruction. problem fix/work around before entering sleep, interrupts not used to wake up the part from the sleep mode should be disabled.
420 7766f?avr?11/10 atmega16/32u4 3. t imer 4 11-bits enhanced pwm mode timer 4 11-bits enhanced mode is not functional. problem fix/work around none. 35.3 atmega16u4/atmega32u4 rev c not sampled 35.4 atmega16u4/atmega32u4 rev b ? spike on twi pins when twi is enabled ? high current consumption in sleep mode ? incorrect execution of vbusti interrupt ? timer 4 11-bits enhanced pwm mode 1. spike on twi pins when twi is enabled 100 ns negative spike occurs on sda and scl pins when twi is enabled. problem fix/work around enable atmega16u4/atmega32u4 twi before the other nodes of the twi network. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected mode, the current consump- tion will increase during sleep when executing the sleep instruction directly after a sei instruction. problem fix/work around before entering sleep, interrupts not used to wake up the part from the sleep mode should be disabled. 3. incorrect execution of vbusti interrupt the cpu may incorrectly execute the interrupt vector related to the vbusti interrupt flag. problem fix/work around do not enable this interrupt. firmware must process this usb event by polling vbusti. 4. t imer 4 11-bits enhanced pwm mode timer 4 11-bits enhanced mode is not functional. problem fix/work around none.
421 7766f?avr?11/10 atmega16/32u4 35.5 atmega16u4/atmega32u4 rev a ? spike on twi pins when twi is enabled ? high current consumption in sleep mode ? increased power consumption in power-down mode ? internal rc oscillato r start up may fail ? internal rc oscillator calibration ? incorrect execution of vbusti interrupt ? timer 4 enhanced mode issue 1. spike on twi pins when twi is enabled 100 ns negative spike occurs on sda and scl pins when twi is enabled. problem fix/work around enable atmega16u4/atmega32u4 twi before the other nodes of the twi network. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected mode, the current consump- tion will increase during sleep when executing the sleep instruction directly after a sei instruction. problem fix/work around before entering sleep, interrupts not used to wake up the part from the sleep mode should be disabled. 3. increased power comsumption in power-down mode the typical power consumption is increased by about 30 a in power-down mode. problem fix/work around none. 4. internal rc oscillator start up may fail when the part is configured to start on internal rc oscillator, the oscillator may not start properly after power-on. problem fix/work around do not configure the part to st art on internal rc oscillator. 5. internal rc oscillator calibration 8 mhz frequency can be impossible to reach with internal rc even when using maximal oscal value. problem fix/work around none. 6. incorrect execution of vbusti interrupt the cpu may incorrectly execute the interrupt vector related to the vbusti interrupt flag. problem fix/work around do not enable this interrupt. firmware must process this usb event by polling vbusti.
422 7766f?avr?11/10 atmega16/32u4 7. t imer 4 11-bits enhanced pwm mode timer 4 11-bits enhanced mode is not functional. problem fix/work around none.
423 7766f?avr?11/10 atmega16/32u4 36. datasheet revision hist ory for atmega16u4/atmega32u4 please note that the referring page numbers in th is section are referred to this document. the referring revision in this section are referring to the document revision. 36.1 rev. 7766f ? 11/10 36.2 rev. 7766e ? 04/10 36.3 rev. 7766d ? 01/09 36.4 rev. 7766c ? 11/08 1. replaced the ?qfn44? on page 418 by an updated drawing. 2. updated ?adc control and status register b ? adcsrb? on page 289 . defined the adcsrb register as in ?adc control and status register b ? adcsrb? on page 312 . 3. updated the last page according to atmel new brand style guide. 1. updated ?features? on page 1 . 2. updated ?features? on page 253 . 3. updated figure 21-9 on page 258 . 4. updated section 21.8 on page 260 . 5. updated ?features? on page 292 . 6. updated ?atmega16u4/atmega32u4 bou ndary-scan order? on page 327 . 7. updated ?program and data memory lock bits? on page 346 . 8. updated table 28-5 on page 348 . 9. updated ?electrical characteristics? on page 378 . 10. updated figure 29-2 on page 381 . 11. added ?typical characteristics? on page 386 . 12. updated ?ordering information? on page 415 . 13. updated ?errata? on page 419 . 1. updated memory section in ?features? on page 1 . 2. added section ?resources? on page 8 . 3. added section ?data retention? on page 8 . 4. updated ?ordering information? on page 415 . 1. updated memory section in ?features? on page 1 .
424 7766f?avr?11/10 atmega16/32u4 36.5 rev. 7766b ? 11/08 36.6 rev. 7766a ? 07/08 1. added atmega16u4 device. 2. created errata section and added atmega16u4. 3. updated high speed timer, asynchronous description section 15. on page 139 1. initial revision
i 7766f?avr?11/10 atmega16/32u4 table of contents 1 pin configurations ..... ................ ................. ................ ................. ............ 3 2 overview ............ ................ ................ ............... .............. .............. ............ 3 2.1block diagram ...........................................................................................................4 2.2pin descriptions ........................................................................................................5 3 about ............. ................ ................. ................ ................. .............. ............ 8 3.1disclaimer ................................................................................................................. .8 3.2resources .................................................................................................................8 3.3code examples .........................................................................................................8 3.4data retention ..........................................................................................................8 4 avr cpu core ................. ................ ................. .............. .............. ............ 9 4.1introduction ............................................................................................................... .9 4.2architectural overview ..............................................................................................9 4.3alu ? arithmetic logic unit ....................................................................................10 4.4status register ........................................................................................................11 4.5general purpose register file ................................................................................12 4.6stack pointer ...........................................................................................................13 4.7instruction execution timing ...................................................................................14 4.8reset and interrupt handling ..................................................................................15 5 avr atmega16u4/atmega32u4 memories .... .............. .............. ........ 18 5.1in-system reprogrammable flash program memory .............................................18 5.2sram data memory ...............................................................................................19 5.3eeprom data memory ...... ................ ................ ................. ............ ............. ..........21 5.4i/o memory ..............................................................................................................26 6 system clock and clock options ................ ................. .............. .......... 27 6.1clock systems and their distribution .......................................................................27 6.2clock sources .........................................................................................................28 6.3low power crystal oscillator ...................................................................................29 6.4low frequency crystal osc illator ............................................................................31 6.5calibrated internal rc oscillator .............................................................................32 6.6external clock .........................................................................................................33 6.7clock switch ............................................................................................................34 6.8clock switch algorithm ............................................................................................35 6.9clock output buffer .................................................................................................37
ii 7766f?avr?11/10 atmega16/32u4 6.10pll ....................................................................................................................... .39 7 power management and sleep mo des ............... .............. ............ ........ 43 7.1idle mode .................................................................................................................4 4 7.2adc noise reduction mode ...................................................................................44 7.3power-down mode ..................................................................................................44 7.4power-save mode ...................................................................................................44 7.5standby mode .........................................................................................................45 7.6extended standby mode .........................................................................................45 7.7power reduction register .......................................................................................45 7.8minimizing power consumption ..............................................................................47 8 system control and reset ...... ................ ................. ................ ............. 49 8.1internal voltage reference ......................................................................................54 8.2watchdog timer ......................................................................................................55 9 interrupts ........ ................. ................ ................. .............. .............. .......... 61 9.1interrupt vectors in atmega16u4/atmega32u4 ....................................................61 10 i/o-ports ........ ................ ................. ................ ................. .............. .......... 65 10.1introduction ............................................................................................................65 10.2ports as general digital i/o ...................................................................................66 10.3alternate port functions ........................................................................................70 10.4register description for i/o-ports ..........................................................................82 11 external interrupts .......... ................ ................. .............. .............. .......... 85 12 timer/counter0, timer/counter1, and timer/counter3 prescalers ... 89 12.1internal clock source ............................................................................................89 12.2prescaler reset .....................................................................................................89 12.3external clock source ...........................................................................................89 12.4general timer/counter control register ? gtccr ..............................................90 13 8-bit timer/counter0 with pw m .............. ................. ................ ............. 91 13.1overview ...............................................................................................................91 13.2timer/counter clock sources ...............................................................................92 13.3counter unit ..........................................................................................................92 13.4output compare unit ............................................................................................93 13.5compare match output unit ..................................................................................95 13.6modes of operation ...............................................................................................96 13.7timer/counter timing diagrams .........................................................................100
iii 7766f?avr?11/10 atmega16/32u4 13.88-bit timer/counter register description ............................................................102 14 16-bit timers/counters (timer/count er1 and timer/counter3) ....... 108 14.1overview .............................................................................................................108 14.2accessing 16-bit registers ..................................................................................110 14.3timer/counter clock sources .............................................................................113 14.4counter unit ........................................................................................................114 14.5input capture unit ...............................................................................................115 14.6output compare units .........................................................................................117 14.7compare match output unit ................................................................................119 14.8modes of operation .............................................................................................120 14.9timer/counter timing diagrams .........................................................................127 14.1016-bit timer/counter register description ........................................................129 15 10-bit high speed time r/counter4 ......... ................. ................ ........... 138 15.1features ..............................................................................................................138 15.2overview .............................................................................................................138 15.3counter unit ........................................................................................................142 15.4output compare unit ..........................................................................................143 15.5dead time generator ..........................................................................................145 15.6compare match output unit ................................................................................146 15.7synchronous update ...........................................................................................149 15.8modes of operation .............................................................................................149 15.9timer/counter timing diagrams .........................................................................156 15.10fault protection unit ..........................................................................................157 15.11accessing 10-bit registers ...............................................................................159 15.12register description ..........................................................................................162 16 output compare modulato r (ocm1c0a) ....... .............. .............. ........ 175 16.1overview .............................................................................................................175 16.2description ..........................................................................................................175 17 serial peripheral interface ? spi ................ ................ .............. ........... 177 17.1ss pin functionality ............................................................................................181 17.2data modes .........................................................................................................184 18 usart ............. ................. ................ .............. .............. .............. ........... 186 18.1overview .............................................................................................................186 18.2clock generation .................................................................................................187
iv 7766f?avr?11/10 atmega16/32u4 18.3frame formats ....................................................................................................190 18.4usart initialization ............................................................................................192 18.5data transmission ? the usart transmitter ....................................................193 18.6data reception ? the usart receiver .............................................................195 18.7asynchronous data reception ............................................................................199 18.8multi-processor communication mode ................................................................202 18.9hardware flow control ........................................................................................203 18.10usart register description .............................................................................205 18.11examples of baud rate setting ........................................................................209 19 usart in spi mode .......... .............. .............. .............. .............. ........... 214 19.1overview .............................................................................................................214 19.2clock generation .................................................................................................214 19.3spi data modes and timing ...............................................................................215 19.4frame formats ....................................................................................................215 19.5data transfer ......................................................................................................217 19.6usart mspim register description ..................................................................219 19.7avr usart mspim vs. avr spi ......................................................................221 20 2-wire serial interface ..... ................ .............. .............. .............. ........... 223 20.1features ..............................................................................................................223 20.22-wire serial interface bus definition ..................................................................223 20.3data transfer and frame format ........................................................................224 20.4multi-master bus systems, arbitration and synchronization ...............................227 20.5overview of the twi module ...............................................................................228 20.6twi register description ....................................................................................231 20.7using the twi ......................................................................................................234 20.8transmission modes ...........................................................................................238 20.9multi-master systems and arbitration ..................................................................251 21 usb controller ................... .............. .............. .............. .............. ........... 253 21.1features ..............................................................................................................253 21.2block diagram .....................................................................................................253 21.3typical application implementation .....................................................................254 21.4crystal-less operation ..........................................................................................256 21.5design guidelines ................................................................................................256 21.6general operating modes ...................................................................................257 21.7power modes ......................................................................................................259
v 7766f?avr?11/10 atmega16/32u4 21.8speed control .....................................................................................................260 21.9memory management .........................................................................................260 21.10pad suspend ....................................................................................................261 21.11plug-in detection ................................................................................................262 21.12registers description .........................................................................................263 21.13usb software operating modes .......................................................................265 22 usb device operating modes ................ ................. ................ ........... 266 22.1introduction ..........................................................................................................266 22.2power-on and reset .............................................................................................266 22.3endpoint reset .....................................................................................................266 22.4usb reset ............................................................................................................267 22.5endpoint selection ...............................................................................................267 22.6endpoint activation ..............................................................................................267 22.7address setup .....................................................................................................268 22.8suspend, wake-up and resume ........................................................................269 22.9detach .................................................................................................................269 22.10remote wake-up ..............................................................................................270 22.11stall request ..................................................................................................270 22.12control endpoint management ....................................................................271 22.13out endpoint management ..............................................................................272 22.14in endpoint management ..................................................................................274 22.15isochronous mode .............................................................................................275 22.16overflow ............................................................................................................276 22.17interrupts ...........................................................................................................276 22.18registers ...........................................................................................................277 23 analog comparator .......... .............. .............. .............. .............. ........... 289 23.1analog comparator multiplexed input .................................................................291 24 analog to digital converte r - adc .............. .............. .............. ........... 292 24.1features ..............................................................................................................292 24.2operation .............................................................................................................294 24.3starting a conversion ..........................................................................................294 24.4prescaling and conversion timing ......................................................................295 24.5changing channel or reference selection .........................................................298 24.6temperature sensor ...........................................................................................299 24.7adc noise canceler ...........................................................................................301
vi 7766f?avr?11/10 atmega16/32u4 24.8adc conversion result ......................................................................................305 24.9adc register description ...................................................................................307 25 jtag interface and on-chi p debug system ............ .............. ........... 314 25.1overview .............................................................................................................314 25.2test access port ? tap ......................................................................................314 25.3tap controller .....................................................................................................316 25.4using the boundary-scan chain ..........................................................................317 25.5using the on-chip debug system .......................................................................317 25.6on-chip debug specific jtag instructions .........................................................318 25.7on-chip debug related register in i/o memory .................................................319 25.8using the jtag programm ing capabilities .........................................................319 25.9bibliography .........................................................................................................319 26 ieee 1149.1 (jtag) boundary-scan ....... ................. ................ ........... 320 26.1features ..............................................................................................................320 26.2system overview ................................................................................................320 26.3data registers .....................................................................................................320 26.4boundary-scan specific jtag instructions .........................................................322 26.5boundary-scan related register in i/o memory .................................................323 26.6boundary-scan chain ..........................................................................................324 26.7atmega16u4/atmega32u4 boundary-scan order ............................................327 26.8boundary-scan description language files ........................................................329 27 boot loader support ? read-while-wri te self-programming ......... 330 27.1boot loader features ..........................................................................................330 27.2application and boot loader flash sections .......................................................330 27.3read-while-write and no read-while-write flash sections ..............................330 27.4boot loader lock bits .........................................................................................333 27.5entering the boot loader program ......................................................................334 27.6addressing the flash during self-programming .................................................337 27.7self-programming the flash ................................................................................338 28 memory programming ........ .............. ............... .............. .............. ........ 346 28.1program and data memory lock bits .................................................................346 28.2fuse bits .............................................................................................................347 28.3signature bytes ...................................................................................................349 28.4calibration byte ...................................................................................................349 28.5parallel programming parameters, pin mapping, and commands .....................349
vii 7766f?avr?11/10 atmega16/32u4 28.6parallel programming ..........................................................................................352 28.7serial downloading .............................................................................................360 28.8serial programming pin mapping ........................................................................361 28.9programming via the jtag interface ..................................................................365 29 electrical characteristics ... .............. ............... .............. .............. ........ 378 29.1absolute maximum ratings* ...............................................................................378 29.2dc characteristics ..............................................................................................378 29.3external clock drive waveforms .........................................................................380 29.4external clock drive ............................................................................................380 29.5maximum speed vs. v cc ............................................................................................................................ . 380 29.62-wire serial interface characteristics .................................................................381 29.7spi timing characteristics ..................................................................................383 29.8hardware boot entrancetiming characteristics ..................................................384 30 typical characteristics ....... .............. ............... .............. .............. ........ 386 30.1active supply current ..........................................................................................386 30.2idle supply current ..............................................................................................389 30.3power-down supply current ...............................................................................391 30.4power-save supply current ................................................................................392 30.5pin pull-up ..........................................................................................................393 30.6pin driver strength ..............................................................................................394 30.7pin threshold and hysteresis .............................................................................397 30.8bod threshold ....................................................................................................400 30.9internal oscilllator speed ....................................................................................402 30.10current consumption of peripheral units ..........................................................405 30.11current consumption in reset and reset pulsewidth ......................................407 31 register summary ............ .............. .............. .............. .............. ........... 408 32 instruction set summary ... .............. ............... .............. .............. ........ 412 33 ordering information .......... .............. ............... .............. .............. ........ 415 33.1atmega16u4 ......................................................................................................415 33.2atmega32u4 ......................................................................................................416 34 packaging information .......... ................ ................. ................ ............. 417 34.1tqfp44 ...............................................................................................................417 34.2qfn44 .................................................................................................................418 35 errata ........... ................ ................ ................. ................ .............. ........... 419
35.1atmega16u4/atmega32u4 rev e ....................................................................419 35.2atmega16u4/atmega32u4 rev d ....................................................................419 35.3atmega16u4/atmega32u4 rev c ....................................................................420 35.4atmega16u4/atmega32u4 rev b ....................................................................420 35.5atmega16u4/atmega32u4 rev a ....................................................................421 36 datasheet revision history for atmega16u4/atmega32u4 ........... 423 36.1rev. 7766f ? 11/10 .............................................................................................423 36.2rev. 7766e ? 04/10 .............................................................................................423 36.3rev. 7766d ? 01/09 ............................................................................................423 36.4rev. 7766c ? 11/08 ............................................................................................424 36.5rev. 7766b ? 11/08 .............................................................................................424 36.6rev. 7766a ? 07/08 .............................................................................................424
7766f?avr?11/10 atmel corporation 2325 orchard parkway san jose, ca 95131 usa tel : (+1)(408) 441-0311 fax : (+1)(408) 487-2600 www.atmel.com atmel asia limited unit 1-5 & 16, 19/f bea tower, millennium city 5 418 kwun tong road kwun tong, kowloon hong kong tel : (+852) 2245-6100 fax : (+852) 2722-1369 atmel munich gmbh business campus parkring 4 d-85748 garching b. munich germany tel : (+49) 89-31970-0 fax : (+49) 89-3194621 atmel japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel : (+81)(3) 3523-3551 fax : (+81)(3) 3523-7581 ? 2010 atmel corporation. all rights reserved. / rev. corp072610 atmel ? , logo and combinations thereof, and others are registered trademarks or trademarks of atmel corporation or its subsidiaries. other terms and product names may be trademarks of others. disclaimer: the information in this document is provided in connection wi th atmel products. no license, ex press or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in the atmel terms and conditions of sales located on the atmel website, atmel assumes no liability whatsoever and disclaims any express, implied or statutory warranty relating to its pro ducts including, but not limited to, the implied warranty of merchantability, fitness for a particular purp ose, or non-infringement. in no even t shall atmel be liable for any direct, indirect, consequential, punitive, special or incidental damages (including, without limitati on, damages for loss and prof- its, business interruption, or loss of information) arising out of the use or inability to use this document, even if atmel has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or com- pleteness of the contents of th is document and reserves the right to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information cont ained herein. unless specifically provided otherwise, atmel pr oducts are not suit- able for, and shall not be used in, automotive applications. atme l products are not intended, authorized, or warranted for use as components in applica- tions intended to support or sustain life.


▲Up To Search▲   

 
Price & Availability of ATXMEGA128A1-CUR

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X